Skip to content

Commit

Permalink
Enable proper iteration over Statevector
Browse files Browse the repository at this point in the history
  • Loading branch information
hristog committed May 13, 2022
1 parent 2d01b4d commit 0f9f3c6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions qiskit/quantum_info/states/statevector.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ def __getitem__(self, key):
else:
raise QiskitError("Key must be int or a valid binary string.")

def __iter__(self):
yield from self._data

@property
def data(self):
"""Return data."""
Expand Down
13 changes: 13 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,19 @@ 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, [x for x in empty_sv])
self.assertEqual(dummy_vector, [x for x in sv])

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

0 comments on commit 0f9f3c6

Please sign in to comment.