How can I get the state vectors at any point in the circuit if after these instructions it points to end.

for d in range(20):

If I use Statevector.from_instruction(qc2) gives only the last, and `QuantumCircuit.get_instructions(name) does not return the entire circuit instructions ordered.


1 Answer 1


You can get the statevector at any point by inserting a SaveStatevector instruction at this point. Then simulating the circuit.

And you can get the list of instructions in the circuit by using QuantumCircuit.data attribute.

For example, this code snippet will insert a SaveStatevector instruction after the third instruction in your circuit:

index = 3
_inst = SaveStatevector(num_qubits)
qc2.data.insert(index, [_inst, qc2.qubits, None])

And this is how to insert a SaveStatevector after each instruction:

from qiskit.providers.aer.library import SaveStatevector

num_qubits = qc2.num_qubits
for index in range(len(qc2.data) - 1, -1, -1):
    _inst = SaveStatevector(num_qubits, label = 'psi_' + str(index))
    qc2.data.insert(index, [_inst, qc2.qubits, None])

This is another example which shows how to insert a SaveStatevector instruction after each layer. This time we are using save_statevector method:

from qiskit.converters import circuit_to_dag, dag_to_circuit

dag = circuit_to_dag(qc2)
new_dag = dag.copy_empty_like()

for index, layer in enumerate(dag.layers()):
    circ = dag_to_circuit(layer['graph'])
    circ.save_statevector('psi_' + str(index))
    layer['graph'] = circuit_to_dag(circ)

qc2 = dag_to_circuit(new_dag)

Now, simulate the circuit to get the statevectors:

from qiskit import Aer
from IPython.display import display

simulator = Aer.get_backend('qasm_simulator')
result = simulator.run(qc2).result()
for key, value in result.data().items():


Starting from version 0.37, QuantumCircuit.decompose() supports a new parameter, reps, which can be used to specify number of times the circuit should be decomposed. So, instead of these two lines of codes:

for d in range(20):

you can simply use:

qc2.decompose(reps = 20)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.