When a Python list is known to always contain a single item, is there way to access it other than:
mylist[0]
You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.
When a Python list is known to always contain a single item, is there way to access it other than:
mylist[0]
You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.
Sequence unpacking:
Explicit use of iterator protocol:
Destructive pop:
Negative index:
Set via single iteration
for
(because the loop variable remains available with its last value when a loop terminates):Many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.
I will add that the
more_itertools
library has a tool that returns one item from an iterable.In addition,
more_itertools.one
raises an error if the iterable is empty or has more than one item.