Skip to content

Commit

Permalink
ObservablesArray docstring improvement (#13423)
Browse files Browse the repository at this point in the history
* ObservablesArray docstring improvement

* Update qiskit/primitives/containers/observables_array.py

Co-authored-by: Elena Peña Tapia <[email protected]>

* Update qiskit/primitives/containers/observables_array.py

Co-authored-by: Elena Peña Tapia <[email protected]>

* Linting

* Added `ObservableLike` as possible return type

---------

Co-authored-by: Elena Peña Tapia <[email protected]>
  • Loading branch information
gadial and ElePT authored Jan 7, 2025
1 parent 0d4ee23 commit b9cba9f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
21 changes: 19 additions & 2 deletions qiskit/primitives/containers/observables_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,25 @@ def __repr__(self):
array = np.array2string(self._array, prefix=prefix, suffix=suffix, threshold=50)
return prefix + array + suffix

def tolist(self) -> list:
"""Convert to a nested list"""
def tolist(self) -> list | ObservableLike:
"""Convert to a nested list.
Similar to Numpy's ``tolist`` method, the level of nesting
depends on the dimension of the observables array. In the
case of dimension 0 the method returns a single observable
(``dict`` in the case of a weighted sum of Paulis) instead of a list.
Examples::
Return values for a one-element list vs one element:
>>> from qiskit.primitives.containers.observables_array import ObservablesArray
>>> oa = ObservablesArray.coerce(["Z"])
>>> print(type(oa.tolist()))
<class 'list'>
>>> oa = ObservablesArray.coerce("Z")
>>> print(type(oa.tolist()))
<class 'dict'>
"""
return self._array.tolist()

def __array__(self, dtype=None, copy=None):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
features_primitives:
- |
Expanded the docstring of :meth:`.ObservablesArray.tolist`
to make it clear it might return a scalar in the case
the observables array is of dimension 0.

0 comments on commit b9cba9f

Please sign in to comment.