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:

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?


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 which works for any Iterable, not just Sequences


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

# non-subscriptable sequences:
assert len(single_item_sequence) == 1

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 could help there, if a concise solution is needed.

1 Like