Apply Hadamard to a list of qubits at the same time

How can I apply Hadamard to a list of qubits without using loops like that in qiskit.

n_bits = 4
dev = qml.device("default.qubit", wires=n_bits)

@qml.qnode(dev)
def appLyHadamard():
    qml.Hadamard(wires=dev.wires) 
# without using this    ' for wire in dev.wires:      qml.Hadamard(wires =wire)'
    return qml.state()

r = appLyHadamard()

I got this error:


ValueError Traceback (most recent call last)
/tmp/ipykernel_51/3241397786.py in <cell line: 1>()
----> 1 r = appLyHadamard()

/opt/conda/envs/pennylane/lib/python3.9/site-packages/pennylane/qnode.py in call(self, *args, **kwargs)
798
799 # construct the tape
→ 800 self.construct(args, kwargs)
801
802 cache = self.execute_kwargs.get(“cache”, False)

/opt/conda/envs/pennylane/lib/python3.9/site-packages/pennylane/qnode.py in construct(self, args, kwargs)
709 “”“Call the quantum function with a tape context, ensuring the operations get queued.”“”
710
→ 711 self._tape = make_qscript(self.func)(*args, **kwargs)
712 self._tape._queue_category = “_ops”
713 self._qfunc_output = self.tape._qfunc_output

/opt/conda/envs/pennylane/lib/python3.9/site-packages/pennylane/tape/qscript.py in wrapper(*args, **kwargs)
1344 def wrapper(*args, **kwargs):
1345 with AnnotatedQueue() as q:
→ 1346 result = fn(*args, **kwargs)
1347
1348 qscript = QuantumScript.from_queue(q)

/tmp/ipykernel_51/935320941.py in appLyHadamard()
4 @qml.qnode(dev)
5 def appLyHadamard():
----> 6 qml.Hadamard(wires=dev.wires)
7 return qml.state()

/opt/conda/envs/pennylane/lib/python3.9/site-packages/pennylane/operation.py in init(self, wires, do_queue, id, *params)
1559
1560 self._inverse = False
→ 1561 super().init(*params, wires=wires, do_queue=do_queue, id=id)
1562
1563 # check the grad_recipe validity

/opt/conda/envs/pennylane/lib/python3.9/site-packages/pennylane/operation.py in init(self, wires, do_queue, id, *params)
880
881 elif len(self._wires) != self.num_wires:
→ 882 raise ValueError(
883 f"{self.name}: wrong number of wires. "
884 f"{len(self._wires)} wires given, {self.num_wires} expected."

ValueError: Hadamard: wrong number of wires. 4 wires given, 1 expected.

Hi @Afrah, great question!

You can use qml.broadcast! This will apply a specific gate multiple times in a certain pattern. You can take a look at the different patterns in the PennyLane docs.

So instead of using qml.Hadamard(wires=dev.wires) you can use qml.broadcast(unitary=qml.Hadamard, pattern="single", wires=dev.wires)

Check out our other templates too :).

Enjoy using PennyLane!