Say, I have a list of operations which are pennylane gates, can I create a circuit from it?

I tried:

import pennylane as qml
operations=[qml.Hadamard(wires=2),qml.PauliX(wires=[2]),qml.PauliX(wires=[3]),qml.CNOT(wires=[1, 2])]
def circuit():
    for op in operations:
    return qml.expval(qml.PauliZ(0))

circuit=qml.QNode(circuit, dev)

This seems not to work. Only the Hadamard on wire 3 is drawn. I do not understand what difference it makes whether I write the gate directly into the circuit or first in a list and then insert it into the circuit.

Is there another way to do this?


2 Answers 2


PennyLane uses queuing under the hood so the issue in your code is that the operations have been instantiated outside of the circuit but haven't been applied to the circuit. You can fix this by simply using qml.apply(op). So you can keep everything as is, but within the for loop you change op to qml.apply(op).

The last Hadamard is already applied because it's instantiated within the circuit.

You can also use qml.draw_mpl() if you want to get nicer drawings of your circuit.

Catalina from PennyLane


Since the operations were already instantiated in list outside of the circuit context, you will have to use qml.apply(operations[0]) and qml.apply(op) instead of just operations[0] or op in the circuit in order for these to be properly picked up.

(under the hood, when you create ops in the circuit function context, some tricks are used to capture this implicitly into your circuit; if you create them outside of the circuit function context, you'll have to explicitly say to apply them)

  • $\begingroup$ Thank you to both of you. Especially, for including some explanation for the behavior. Unfortunately, I can only mark one of the answers as 'the answer'. $\endgroup$ Commented Sep 28, 2022 at 7:50

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.