Swap gate

The Swap gate: matrix, effect on the basis states, the swap() call in Python and JS, and why it costs three entangling gates on IonQ hardware.

The Swap gate exchanges the states of two qubits: whatever the first qubit held, the second holds afterwards, and the other way round. It acts on two qubits and takes no parameters. The Circuit panel draws a Swap box on each of the two wires, joined by a line.

Kets such as 0\vert 0 \rangle name the basis states and rotations are described on the Bloch sphere; the qubits lesson introduces both.

Call

WhereCall
Pythonqc.swap(qubit1, qubit2)
JScircuit.swap(qubit1, qubit2)
Qiskit classSwapGate

Matrix

The matrix uses the basis order 00,01,10,11\vert 00 \rangle, \vert 01 \rangle, \vert 10 \rangle, \vert 11 \rangle.

SWAP=(1000001001000001)SWAP = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}

Effect on basis states

InputOutput
00\vert 00 \rangle00\vert 00 \rangle
01\vert 01 \rangle10\vert 10 \rangle
10\vert 10 \rangle01\vert 01 \rangle
11\vert 11 \rangle11\vert 11 \rangle

The exchange holds for superpositions and entangled states too: Swap moves the whole state of each qubit, phases included.

Inverse

Swap is its own inverse. Two Swap gates in a row on the same pair cancel.

Usage

from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)
qc.x(0)
qc.swap(0, 1)
qc.measure([0, 1], [0, 1])
import { QuantumCircuit } from 'qiskit';

const circuit = QuantumCircuit(2, 2);
circuit.x(0);
circuit.swap(0, 1);
circuit.measure([0, 1], [0, 1]);

Every shot reads qubit 0 as 0 and qubit 1 as 1: the X put a 1 on qubit 0 and the Swap moved it. In Qiskit's count strings, which list the highest qubit first, that is 10.

On IonQ hardware

Swap is not a native gate and has no one-gate form. Its standard decomposition is three CX gates, cx(a, b), cx(b, a), cx(a, b), so a Swap costs three entangling gates before IonQ's optimiser runs, three times a CX. It is also the one gate IonQ does not accept in a controlled form. See How your circuit is compiled.

Stay in the loop.

Get the latest tutorials, demos, and project showcases straight to your inbox. No noise, just the good stuff.