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
