liveBook · Manning

QuantumRegister

As explained in Building Quantum Software with Python

A quantum register is a grouped collection of qubits used to represent a multi-bit quantum value or variable.

A QuantumRegister groups qubits that represent one multi-bit value or variable. Registers give their qubits local indexes, while a circuit maps those indexes into the full system. section 2.2.1 section 4.5.2

Use a register to organize qubits and connect them to circuit operations:

  • Choose its size from the range of values the variable must represent. section 2.2.1
  • Access qubits with zero-based indexing, slicing, iteration, or reversed iteration. section 4.5.2
  • Pass register elements to gate methods as targets or controls; circuits assign each register a system-wide shift. section 4.5.2
  • Combine multiple registers to separate related variables, such as a selection, its value, and its weight. section 2.2.1 section 11.3.1

Three-qubit circuit

q = QuantumRegister(3)\nqc = QuantumCircuit(q)\nqc.h(q[0])\nqc.h(q[1])\nqc.mcx([q[0], q[1]], q[2])\nstate = qc.run() section 4.5.2

Listing 4.8 QuantumRegister class
class QuantumRegister:
    def __init__(self, size, shift=0):
        self.size = size
        self.shift = shift

    def __getitem__(self, key):
        if isinstance(key, slice):
            return [self[ii] for ii in range(*key.indices(len(self)))]
        elif isinstance(key, int):
            if key < 0:
                key += len(self)
            assert(0 <= key < self.size)
            return self.shift + key

    def __len__(self):
        return self.size

    def __iter__(self):
        return list([self.shift + i for i in range(self.size)])

    def __reversed__(self):
        return list([self.shift + i for i in range(self.size)[::-1]])

Inspect the compact Python implementation showing size storage, index validation, offsets, slicing, and iteration. section 4.5.2

How Building Quantum Software with Python covers it

How deep it goes
Defines construction, indexing, slicing, iteration, and circuit offsets, while deferring further circuit methods to later extensions.
Examples
Uses knapsack registers, a three-qubit circuit, indexed gate calls, and key–value or function encodings across separate registers.
What it assumes
Assumes qubits, binary outcomes, quantum gates, and circuits while establishing register sizing and local-to-global indexing.
What you can do after
Builds multi-register circuits and addresses target or control qubits through a small Python register API.
How it connects
Connects qubits with quantum circuits, quantum gates, controlled gates, measurement outcomes, and quantum state encoding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Quantum Software with Python. The section links point to the parts of the book it draws on.