Skip to content

Commit

Permalink
Enable proper iteration over Statevector (Qiskit#8062)
Browse files Browse the repository at this point in the history
* Enable proper iteration over Statevector

* Add Statevector.__len__ and add a release note

* Simplify release note

* Update test_statevctor_iter

Co-authored-by: Jake Lishman <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored and ajavadia committed May 31, 2022
1 parent 5f4da20 commit a7a885e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
6 changes: 6 additions & 0 deletions qiskit/quantum_info/states/statevector.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ def __getitem__(self, key):
else:
raise QiskitError("Key must be int or a valid binary string.")

def __iter__(self):
yield from self._data

def __len__(self):
return len(self._data)

@property
def data(self):
"""Return data."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
:class:`.Statevector` will now allow direct iteration through its values
(such as ``for coefficient in statevector``) and
correctly report its length under ``len``. Previously it would try and
and access out-of-bounds data and raise a :class:`.QiskitError`. See
`#8039 <https://github.com/Qiskit/qiskit-terra/issues/8039>`__.
23 changes: 23 additions & 0 deletions test/python/quantum_info/states/test_statevector.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,29 @@ def test_statevector_draw_latex_regression(self):
self.assertTrue(latex_string.startswith(" |0\\rangle"))
self.assertNotIn("|1\\rangle", latex_string)

def test_statevctor_iter(self):
"""Test iteration over a state vector"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)

# Assert that successive iterations behave as expected, i.e., the
# iterator is reset upon each exhaustion of the corresponding
# collection of elements.
for _ in range(2):
self.assertEqual(empty_vector, list(empty_sv))
self.assertEqual(dummy_vector, list(sv))

def test_statevector_len(self):
"""Test state vector length"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)
self.assertEqual(len(empty_vector), len(empty_sv))
self.assertEqual(len(dummy_vector), len(sv))


if __name__ == "__main__":
unittest.main()

0 comments on commit a7a885e

Please sign in to comment.