Skip to content

Commit b9cba9f

Browse files
gadialElePT
andauthored
ObservablesArray docstring improvement (Qiskit#13423)
* 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]>
1 parent 0d4ee23 commit b9cba9f

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

qiskit/primitives/containers/observables_array.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,25 @@ def __repr__(self):
9797
array = np.array2string(self._array, prefix=prefix, suffix=suffix, threshold=50)
9898
return prefix + array + suffix
9999

100-
def tolist(self) -> list:
101-
"""Convert to a nested list"""
100+
def tolist(self) -> list | ObservableLike:
101+
"""Convert to a nested list.
102+
103+
Similar to Numpy's ``tolist`` method, the level of nesting
104+
depends on the dimension of the observables array. In the
105+
case of dimension 0 the method returns a single observable
106+
(``dict`` in the case of a weighted sum of Paulis) instead of a list.
107+
108+
Examples::
109+
Return values for a one-element list vs one element:
110+
111+
>>> from qiskit.primitives.containers.observables_array import ObservablesArray
112+
>>> oa = ObservablesArray.coerce(["Z"])
113+
>>> print(type(oa.tolist()))
114+
<class 'list'>
115+
>>> oa = ObservablesArray.coerce("Z")
116+
>>> print(type(oa.tolist()))
117+
<class 'dict'>
118+
"""
102119
return self._array.tolist()
103120

104121
def __array__(self, dtype=None, copy=None):
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
features_primitives:
3+
- |
4+
Expanded the docstring of :meth:`.ObservablesArray.tolist`
5+
to make it clear it might return a scalar in the case
6+
the observables array is of dimension 0.

0 commit comments

Comments
 (0)