# If_test() - Dynamic Circuits in qiskit

I am trying to run a dynamic circuit by having mid-measurement in my code as follows:

from qiskit import *
from math import *
from qiskit.providers.fake_provider import FakeJakarta

backend = FakeJakarta()

q0 = QuantumRegister(1)
q1 = QuantumRegister(1)
c  = ClassicalRegister(2)
qc = QuantumCircuit(q0, q1, c)
result_ = []
for i in range(2):
qc.ry(2*pi/3, q0)
qc.cx(q0, q1)
qc.h(q1)
qc.measure(q1, c[i])
with qc.if_test((c[i], 0)) as _else:
result_.append(0)
with _else:
result_.append(1)
job = backend.run(qc)
print(result_)


As it is obvious we must have a result like [0, 1, 0]. However, the list that I receive always is [0, 1, 0, 1]. Does anyone know how to solve this matter?

• Do you mind writing the rest of your code? Not sure what this suppose to do. Nov 17 at 20:13
• Thank you so much for your reply. I completed the code as you can see it. Nov 17 at 20:40
• Could you please clarify your objective with this circuit? Are you trying to create a list that dynamically changes based on the quantum measurement results within each iteration of your loop? Or are you attempting to modify the quantum circuit's behavior based on previous measurement outcomes? Nov 18 at 11:54
• The goal which I am seaking to achieve in here is that I am trying to gather measurement data from each iteration. For example, if we consider three iterations, what we should have is something like [1, 0 , 1] , But it gives us [0, 1, 0, 1, 0, 1]. Nov 18 at 12:08

It appears there's a misunderstanding regarding the use of if_test and _else constructs in your code. In Qiskit, these constructs are for adding conditional quantum operations to the circuit based on classical register states, not for controlling the flow of Python code execution. Consequently, in your loop, both result_.append(0) and result_.append(1) are executed in each iteration, leading to a list that's twice as long as expected. Also, you should only expect a list of length two as your result (not three), as you are measuring with classical bit c in the first iteration, and c in the second iteration.

Here's a (potential) version of your code that gathers measurement data from each iteration (if I am correct in interpreting this you want to do):

from qiskit import *
from math import *
from qiskit.providers.fake_provider import FakeJakarta

backend = FakeJakarta()

q0 = QuantumRegister(1)
q1 = QuantumRegister(1)
c  = ClassicalRegister(2)
qc = QuantumCircuit(q0, q1, c)

results = []

for i in range(2):
qc.ry(2*pi/3, q0)
qc.cx(q0, q1)
qc.h(q1)
qc.measure(q1, c[i])
job = backend.run(qc, shots=1)
result = job.result().get_counts(qc)
results.append(result)

print(results)

• Thank you so much for your nice explanation. I have found an alternative that can do my proposed task. SwitchCase operation will the best and only option! Nov 19 at 20:16