Cirq Fundamentals

Lesson 3 of 8

Quantum Gates

Cirq ships the same core gate set you'd expect from any quantum SDK, applied through the operation pattern from lesson 1: gate(qubit).

Single-qubit gates

import cirq

q = cirq.LineQubit(0)
circuit = cirq.Circuit()
circuit.append(cirq.X(q))  # NOT: flips |0> <-> |1>
circuit.append(cirq.Z(q))  # flips the sign of the |1> amplitude
circuit.append(cirq.H(q))  # Hadamard: creates/undoes superposition

print(circuit)

Exactly the same roles as Qiskit's x, z, and h, X for a classical-style flip, H for superposition, Z mostly useful combined with other gates.

A two-qubit gate: CNOT

q0, q1 = cirq.LineQubit.range(2)

circuit = cirq.Circuit()
circuit.append(cirq.H(q0))          # put q0 into superposition
circuit.append(cirq.X(q1))          # flip q1 to |1>
circuit.append(cirq.CNOT(q0, q1))   # flip q1 IF q0 measures as |1>

print(circuit)

cirq.LineQubit.range(2) is a convenience for creating multiple qubits at once, equivalent to [cirq.LineQubit(0), cirq.LineQubit(1)]. cirq.CNOT(control, target) behaves identically to Qiskit's cx, it's the gate that lets one qubit's state influence another, the mechanism behind entanglement.

Chaining operations

Appending accepts a single operation or a list, both build up the circuit the same way:

q0, q1, q2 = cirq.LineQubit.range(3)

circuit = cirq.Circuit([
    cirq.H(q0),
    cirq.CNOT(q0, q1),
    cirq.CNOT(q1, q2),
    cirq.X(q2),
])

print(circuit)

Passing a list directly to cirq.Circuit([...]) is a common shorthand once you know every operation you want up front, rather than calling .append() repeatedly.

NOTE

Cirq operations are just as reversible as Qiskit's, the underlying physics of quantum gates doesn't depend on which SDK you're using, only the Python syntax for expressing it changes.

📝 Quantum Gates Quiz

Passing score: 70%
  1. 1.What does cirq.CNOT(q0, q1) do?

  2. 2.cirq.LineQubit.range(3) is a shorthand for creating 3 LineQubits at once.

  3. 3.circuit.append(...) accepts either a single operation or a ____ of operations.