PrimeIntellect/SWE-rebench-V2 huggingface dataset:
Repository: Qiskit/qiskit-terra (python)

Issue:
QuantumCircuit.remove_final_measurements leaves remnant classical bits?
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: 0.16.3
- **Python version**: 
- **Operating system**:

### What is the current behavior?
`QuantumCircuit.remove_final_measurements()` removes the idle classical registers - just as its docstring states - but not the associated classical bits.

### Steps to reproduce the problem

```python
from qiskit import QuantumCircuit

qc = QuantumCircuit(1,1)
qc.measure(0,0)
qc.remove_final_measurements()

assert len(qc.cregs)==0, "idle classical register not removed"
assert len(qc.clbits)==0, f"idle classical bits not removed: {qc.clbits}"
```

### What is the expected behavior?



### Suggested solutions
If the above behavior is not intended, `circ.clbits.clear()` before parsing the new circuit DAG for active classical bits?

Pull request:
Clean QuantumCircuit.clbits after QuantumCircuit.remove_final_measurements
Fixes #5802

After `circuit.remove_final_measurements()`, `circuit.clbits` property is not being updated.

Patch:
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py
index ef40b553e..e6e472a05 100644
--- a/qiskit/circuit/quantumcircuit.py
+++ b/qiskit/circuit/quantumcircuit.py
@@ -1748,6 +1748,8 @@ class QuantumCircuit:
             inst.condition = node.condition
             circ.append(inst, qubits, clbits)
 
+        circ.clbits.clear()
+
         if not inplace:
             return circ
         else:


Test patch:
diff --git a/test/python/circuit/test_circuit_operations.py b/test/python/circuit/test_circuit_operations.py
index 448d59cb8..311f90762 100644
--- a/test/python/circuit/test_circuit_operations.py
+++ b/test/python/circuit/test_circuit_operations.py
@@ -363,6 +363,20 @@ class TestCircuitOperations(QiskitTestCase):
 
         self.assertEqual(expected, circuit)
 
+    def test_remove_final_measurements_5802(self):
+        """Test remove_final_measurements removes classical bits
+        https://github.com/Qiskit/qiskit-terra/issues/5802.
+        """
+        qr = QuantumRegister(2)
+        cr = ClassicalRegister(2)
+
+        circuit = QuantumCircuit(qr, cr)
+        circuit.measure(qr, cr)
+        circuit.remove_final_measurements()
+
+        self.assertEqual(circuit.cregs, [])
+        self.assertEqual(circuit.clbits, [])
+
     def test_reverse(self):
         """Test reverse method reverses but does not invert."""
         qc = QuantumCircuit(2, 2)