# Can I remove gates from a QuantumCircuit?

Suppose I want to implement run several circuits one after another, but they are constructed in a similar fashion. I could reinstantiate a QuantumCircuit for each iteration, like this:

params = np.linspace(0, 2 * np.pi, num=20)
for p in params:
circ = QuantumCircuit(q, c)
do_stuff(circ, p)
do_other_stuff()


but I'm afraid that creating a bunch of unnecessary circ objects takes too much memory or too many calls to the garbage collector.

Instead, I would like to remove the gates from the QuantumCircuit object and build the new circuit in the old object. Is it possible, and if so, is it reasonable?

## 1 Answer

Quantum circuits have a data attribute, which is a list of all gates. You can remove elements from this as with any Python list. For example, here's a circuit

q = QuantumRegister(1)
circ = QuantumCircuit(q)

circ.h(q)
circ.s(q)
circ.x(q)


Let's get rid of the S gate. First, we can look at the list of gates with circ.data. This gives

[<qiskit.extensions.standard.h.HGate at 0x11721b7b8>,
<qiskit.extensions.standard.s.SGate at 0x11721b828>,
<qiskit.extensions.standard.x.XGate at 0x11721b7f0>]


Element 1 of this list (i.e. the second element) is the gate we want rid of. We can do this with pop.

qiskit.data.pop(1)


The resulting circuit can then be seen by print(circ)

         ┌───┐┌───┐
q0_0: |0>┤ H ├┤ X ├
└───┘└───┘


As you can see, we have succeeded in removing the S gate.

Note that you can get information about the elements of the data list using the methods name and qargs, etc, of gate objects. For example, to see that element 0 is a Hadamard, and to see which qubit it acts on, we can use

print( circ.data.name )
print( circ.data.qargs )


This returns

h
[(QuantumRegister(1, 'q0'), 0)]