Introduction of `tuple.item()` / `list.item()` / `Sequence.item()` to convert sequence to scalar

I propose to introduce list.item() and tuple.item() (and possibly Sequence.item() in general) as a concise way to convert sequences with of length 1 to a scalar value, the same as NumPy does:

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html

What do you think?

item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned.

In the core Python data types, there would be no difference, so why use a method instead of simply subscripting?

3 Likes

For regular Python, especially the no-args case is relevant:

in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned.

If len(a) != 1, a ValueError would be raised. This would be one core benefit.

You can use more_itertools.one which works for any Iterable, not just Sequences

https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.one

2 Likes

For this we can do:

single_item_sequence = [1]


# For assignments use unpacking:

item, = single_item_sequence

# Use brackets to make it easier to notice the comma.
(item,) = single_item_sequence


# For expressions use assert and the indexing operator:

assert len(single_item_sequence) == 1
print(single_item_sequence[0])

# non-subscriptable sequences:
assert len(single_item_sequence) == 1
print(tuple(single_item_sequence)[0])

I think we do not need this frequently enough to have a special method for that.

Thanks, these are some useful suggestions! I don’t like the assert construct very much, but more_itertools.one could help there, if a concise solution is needed.

1 Like