Dynamic qml.expval operation

Actually I was trying to run a function where we had to do expval operation. For, example, we have if we have 3 wires, we can manually do -
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2))

But, I am not understanding how to let the function do it dynamically if we just input the number of wires, so that the expval of all the wires are done automatically and returned to me as an output.
For, example, if n= 5, it should give this as return-
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2)@ qml.PauliZ(3) @ qml.PauliZ(4)

Thanks in advance :slightly_smiling_face:

Hi @AKSHITA1,

You can do this by creating an observable with a for loop within the circuit function and then you calculate the expectation value of that observable. Here’s an example of how this can look:

import pennylane as qml

n_wires = 5
wires = list(range(n_wires))

dev = qml.device('default.qubit', wires=wires)

@qml.qnode(dev)
def circuit():
    qml.Hadamard(wires[-1])
    qml.MultiControlledX(wires=wires)
    qml.Hadamard(wires[-1])
    
    observable = qml.PauliZ(0)
    for i in range(n_wires-1):
        observable = observable@(qml.PauliZ(i+1))
    return qml.expval(observable)

qml.draw_mpl(circuit)()

I hope this works for your particular case!