Let's start from a basic example: suppose I have the following list containing $N=8$ non-negative ints:

L = [2, 1, 2, 0, 0, 1, 3, 2]

I want to encode the whole list $L$ into a quantum state $|\psi\rangle$ by using basis encoding as follows:

$$|\psi \rangle = \frac{1}{\sqrt{N}} \sum_{i=0}^{N-1} |L_i\rangle |i\rangle$$

where $|L_i\rangle$ is the $i$-th element in the list, and $|i\rangle$ is its corresponding index (both represented as bit-strings). In this example, I would get an equal superposition of the states $|10\rangle|000\rangle$ ($L_0=2$), $|01\rangle|001\rangle$ ($L_1=1$), and so on until $|10\rangle|111\rangle$ ($L_7=2$).

Is there a way in Qiskit to prepare this state given an arbitrary Python list? And, if not, how could it be implemented?


2 Answers 2


This is the implementation of my own solution (it only works well when $L_i\in \mathbb{N}$ and len(L) is a power of 2 but could be easily extended to a more general case):

import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import StatePreparation

L = [2, 1, 2, 0, 0, 1, 3, 2]

len_qr1 = int(np.ceil(np.log2(len(L))))
len_qr2 = int(np.log2(max(L))) + 1
num_qubits = len_qr1 + len_qr2
statevector = np.zeros(2**num_qubits)

for i, el in enumerate(L):
    index_reg = '{0:b}'.format(i).zfill(len_qr1)
    element_reg = '{0:b}'.format(el).zfill(len_qr2)
    statevector[int(element_reg + index_reg, 2)] = 1

statevector /= np.linalg.norm(statevector)

qc = QuantumCircuit(num_qubits)
sp = StatePreparation(statevector)
qc.append(sp, range(num_qubits))

Running the qc circuit 10000 times by using the qasm_simulator to measure the final state $|\psi\rangle$, I get the expected distribution (equal superposition of the 8 bit-strings):

enter image description here

import numpy as np
import numpy.linalg as la

L = [2, 1, 2, 0, 0, 1, 3, 2]
L = np.array(L, dtype=float)

qc = QuantumCircuit(3)
qc.prepare_state(L / la.norm(L))

You can also use initialize instead of prepare_state. The former resets the qubits to zero first (which isn't necessary here) while the latter generates an invertible gate.

  • $\begingroup$ Ok but this is "amplitude encoding". I want to encode my list by using "basis encoding" as described in the question $\endgroup$ Commented Dec 14, 2022 at 23:21
  • 1
    $\begingroup$ So just create a state vector with 32 elements and the items that you want to have equal probability set to 1 and the rest set to 0. Normalize and call prepare_state as above. $\endgroup$ Commented Dec 15, 2022 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.