1
$\begingroup$

Below Qiskit snippet throws error - CircuitError: 'Index 1 out of range for size 1.. What's wrong?

import qiskit
number_of_qubits = 1 
initial_state = [0,1]
qc = qiskit.QuantumCircuit(number_of_qubits)
qc.initialize(initial_state)
qc.x(initial_state)
qc.draw()

Error trace:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\my_custom_virtualenvs\qiskit_env\lib\site-packages\qiskit\circuit\quantumcircuit.py:4939, in _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_)
   4938 try:
-> 4939     return bit_sequence[specifier]
   4940 except IndexError as ex:

IndexError: list index out of range

The above exception was the direct cause of the following exception:

CircuitError                              Traceback (most recent call last)
Input In [15], in <cell line: 6>()
      4 qc = qiskit.QuantumCircuit(number_of_qubits)
      5 qc.initialize(initial_state[1])
----> 6 qc.x(initial_state)
      7 qc.draw()

...
CircuitError: 'Index 1 out of range for size 1.'

```
$\endgroup$

1 Answer 1

1
$\begingroup$

You are applying X to two qubits, [0,1]. However, your circuit has only one. You can change your code to:

import qiskit
number_of_qubits = 1
initial_state = [0,1]
qc = qiskit.QuantumCircuit(number_of_qubits)
qc.initialize(initial_state)
qc.x(0)
qc.draw()
   ┌─────────────────┐┌───┐
q: ┤ Initialize(0,1) ├┤ X ├
   └─────────────────┘└───┘
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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