|q⟩ Bad Qubits

beginner · Programming · Single-Qubit Gates I: X, Y, Z

Composing Gates

Quantum gates are linear maps, and like all linear maps they can be chained: the output of one gate becomes the input of the next. A sequence of gates is called a circuit, and reading it left to right tells you the order in which the operations are applied to the state.

Gate sequences as matrix products

Suppose you apply gate AA and then gate BB to a state ψ|\psi\rangle. The result is

B(Aψ)=(BA)ψ.B\bigl(A|\psi\rangle\bigr) = (BA)|\psi\rangle.

Notice the reversal: in matrix notation the rightmost factor is applied first. When you write code, however, you list the operations in the order they are applied — first AA, then BB — which matches the way you read a timeline.

A worked example: X then Z

Starting from 0|0\rangle, apply XX and then ZZ:

  1. X0=1X|0\rangle = |1\rangle — the NOT gate flips the bit.
  2. Z1=1Z|1\rangle = -|1\rangle — Z multiplies the 1|1\rangle amplitude by 1-1.

So the final state is 1-|1\rangle. The overall operation can be written as a single matrix product:

ZX=(1001)(0110)=(0110).ZX = \begin{pmatrix}1&0\\0&-1\end{pmatrix}\begin{pmatrix}0&1\\1&0\end{pmatrix} = \begin{pmatrix}0&1\\-1&0\end{pmatrix}.

You can verify: (ZX)0=(01)=1(ZX)|0\rangle = \binom{0}{-1} = -|1\rangle, matching the step-by-step calculation.

Order matters

Swapping the order to ZZ first and then XX gives a different state:

0ZZ0=0XX0=1.|0\rangle \xrightarrow{Z} Z|0\rangle = |0\rangle \xrightarrow{X} X|0\rangle = |1\rangle.

Step by step:

  1. Z0=0Z|0\rangle = |0\rangle — Z leaves 0|0\rangle unchanged (it only introduces a sign on 1|1\rangle).
  2. X0=1X|0\rangle = |1\rangle.

The final state is 1|1\rangle, which differs from 1-|1\rangle only by a global phase of 1-1. Because XX and ZZ anti-commute (XZ=ZXXZ = -ZX), every pair of states produced by the two orderings is related by this global phase of 1-1 for any input — so the two orderings are never measurably distinguishable on their own. In contrast, gate pairs that neither commute nor anti-commute (such as TT and XX) can produce states that differ by a relative phase, which does affect measurement statistics in a larger circuit.

Try it

Apply XX and then ZZ to qubit 0, starting from 0|0\rangle. The grader checks the full state vector — the sign of the amplitude matters here.

Run your code to see the quantum state.

After running, you should see that all the probability sits on 1|1\rangle (as expected — the qubit is definitely 11) but the amplitude is 1-1, not +1+1. That minus sign is the imprint of ZZ.

Sign in on the full site to ask questions and join the discussion.