Code exampleBeginnermeasurement

Measuring in the X, Y and Z Bases

Measure |+⟩ and |i+⟩ in all three bases by adding basis-change gates before measurement.

For the $X$ basis we add H before measurement, and for the $Y$ basis we add $S^\dagger$ then H. The state $|+\rangle$ is deterministic in $X$ and random in $Y$ and $Z$, and the state $|i+\rangle$ is deterministic in $Y$ and random in $X$ and $Z$. The roughly equal counts in the random lines are identical across lines because the primitive uses the same seed in every call.

Requirements: pip install qiskit qiskit-aer. The code runs on your machine or in Colab, not inside WordPress.

Code

Qiskit
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler


def measure_in(basis, prepare):
    qc = QuantumCircuit(1)
    prepare(qc)
    if basis == "x":
        qc.h(0)
    elif basis == "y":
        qc.sdg(0)
        qc.h(0)
    qc.measure_all()
    return qc


states = {"|+>": lambda qc: qc.h(0), "|i+>": lambda qc: (qc.h(0), qc.s(0))}
sampler = StatevectorSampler(seed=9)
for name, prep in states.items():
    for basis in ["z", "x", "y"]:
        counts = sampler.run([measure_in(basis, prep)], shots=1000).result()[0].data.meas.get_counts()
        print(name, basis, dict(sorted(counts.items())))

Line-by-line code explanation

LineExplanation
1-2Imports.
5A function that builds a measurement circuit in a given basis.
6-7A one-qubit circuit and state preparation.
8-9X basis: Hadamard.
10-12Y basis: S† then Hadamard.
13Measure in Z after the change of basis.
14Return the circuit.
17Prepare |+⟩ and prepare |i+⟩ (H then S).
18A primitive with seed 9.
19-20Each state in each basis.
211000 shots.
22Print.

Expected output (from an actual run)

|+> z {'0': 503, '1': 497}
|+> x {'0': 1000}
|+> y {'0': 503, '1': 497}
|i+> z {'0': 503, '1': 497}
|i+> x {'0': 503, '1': 497}
|i+> y {'0': 1000}

Counts from StatevectorSampler(seed=9); the deterministic lines do not depend on the seed.

Try it yourself

Related topics

References

  1. IBM Quantum (2025). Qiskit SDK API documentation. IBM Quantum Documentation quantum.cloud.ibm.com
  2. Michael A. Nielsen; Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press doi:10.1017/CBO9780511976667The standard reference for quantum computing; the Crossref record gives 2012 for the Cambridge Core online edition.