Skip to main content
2 of 2
added 203 characters in body
Egretta.Thula
  • 11.8k
  • 1
  • 13
  • 34

Update: @Kevin Lively provides a better answer.


Here is a function to remove the idle wires. However, it has the drawback that you will lose the registers info:

from qiskit.converters import circuit_to_dag, dag_to_circuit
from collections import OrderedDict

def remove_idle_qwires(circ):
    dag = circuit_to_dag(circ)

    idle_wires = list(dag.idle_wires())
    for w in idle_wires:
        dag._remove_idle_wire(w)
        dag.qubits.remove(w)

    dag.qregs = OrderedDict()

    return dag_to_circuit(dag)

Now, let's create a multi-register circuit with some idle wires and use it to check the solution:

q = QuantumRegister(2, 'q')
a = QuantumRegister(2, 'a')
circ = QuantumCircuit(q, a)
circ.h(q[0])
circ.cx(q[0], a[0])
circ.draw('mpl')

enter image description here

circ2 = remove_idle_qwires(circ)
circ2.draw('mpl')

enter image description here

Egretta.Thula
  • 11.8k
  • 1
  • 13
  • 34