#8032·qiskit

Support slice-indexing in `Statevector`

Author: taketakeyyyCreated May 9, 2022Updated Sep 18, 2026
Labelstype: feature request

Environment

  • Qiskit Terra version: 0.20.1

  • Python version: 3.10.4

  • Operating system: Windows 10

  • Others

    • qiskit-aer: 0.10.4
    • qiskit-ignis: 0.7.0
    • qiskit-ibmq-provider: 0.19.1
    • qiskit: 0.36.1

What is happening?

Exercises not working due to Statevector class not accepting slices.

How can we reproduce the issue?

Go to https://qiskit.org/textbook/ch-algorithms/bernstein-vazirani.html, and try exercises.

python
from qiskit_textbook.widgets import bv_widget
bv_widget(3, "011", hide_oracle=False)

It doesn't work no matter which button I click.

What should happen?

Exercises works.

Any suggestions?

There is an error in the following part of bv_widget.

python
vfirst = vec[:2**nqubits//2]

vec is Statevector class. The Statevector class does not accept slice and raises QiskitError("Key must be int or a valid binary string.").

python
    def __getitem__(self, key):
        """Return Statevector item either by index or binary label
        Args:
            key (int or str): index or corresponding binary label, e.g. '01' = 1.

        Returns:
            numpy.complex128: Statevector item.

        Raises:
            QiskitError: if key is not valid.
        """
        if isinstance(key, str):
            try:
                key = int(key, 2)
            except ValueError:
                raise QiskitError(f"Key '{key}' is not a valid binary string.") from None
        if isinstance(key, int):
            if key >= self.dim:
                raise QiskitError(f"Key {key} is greater than Statevector dimension {self.dim}.")
            if key < 0:
                raise QiskitError(f"Key {key} is not a valid positive value.")
            return self._data[key]
        else:
            raise QiskitError("Key must be int or a valid binary string.")

I think the following change would solve the problem.

python
    def __getitem__(self, key):
        """Return Statevector item either by index or binary label
        Args:
            key (int or str): index or corresponding binary label, e.g. '01' = 1.

        Returns:
            numpy.complex128: Statevector item.

        Raises:
            QiskitError: if key is not valid.
        """
        if isinstance(key, str):
            try:
                key = int(key, 2)
            except ValueError:
                raise QiskitError(f"Key '{key}' is not a valid binary string.") from None
        if isinstance(key, int):
            if key >= self.dim:
                raise QiskitError(f"Key {key} is greater than Statevector dimension {self.dim}.")
            if key < 0:
                raise QiskitError(f"Key {key} is not a valid positive value.")
            return self._data[key]

        """ From here """
        if isinstance(key, slice):
            return self._data[key]
        """ Until here """

        else:
            raise QiskitError("Key must be int or a valid binary string.")