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:
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.
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.