When a Python list is known to always contain a single item, is there a 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.
singleitem, = mylist
# Identical in behavior (byte code produced is the same),
# but arguably more readable since a lone trailing comma could be missed:
[singleitem] = mylist
lambda
function:# The only even semi-reasonable way to retrieve a single item and raise an exception on
# failure for too many, not just too few, elements as an expression, rather than a
# statement, without resorting to defining/importing functions elsewhere to do the work
singleitem = (lambda x: x)(*mylist)
singleitem = next(iter(mylist))
singleitem = mylist.pop()
singleitem = mylist[-1]
for
(because the loop variable remains available with its last value when a loop terminates):for singleitem in mylist: break
There are many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.
[]
for sequence unpacking (for [i, x] in enumerate(iterable):
drives me batty), but yes, in the case of unpacking a single value, the trailing comma can easily be missed, and using brackets is justifiable for readability reasons. I've added it to the answer. Thanks!
Oct 16, 2015 at 14:47
_
(making an empty list
there if it's in fact single element); it's otherwise identical to singleitem, = mylist
.
Nov 30, 2020 at 11:46
I will add that the more_itertools
library has a tool that returns one item from an iterable.
from more_itertools import one
iterable = ["foo"]
one(iterable)
# "foo"
In addition, more_itertools.one
raises an error if the iterable is empty or has more than one item.
iterable = []
one(iterable)
# ValueError: not enough values to unpack (expected 1, got 0)
iterable = ["foo", "bar"]
one(iterable)
# ValueError: too many values to unpack (expected 1)
more_itertools
is a third-party package > pip install more-itertools
more_itertools.one
was exactly equivalent to my primary solution, aside from variable names (a two-liner, element, = iterable
, then return element
). It's since gotten much more complex (allowing custom exceptions for too short or too long, and therefore unable to benefit from unpacking performing the work efficiently, with Python raising exceptions for you). It's kind of a shame; it's rare the distinction matters, yet the code got much slower to accommodate it.
Jan 20 at 19:31
(This is an adjusted repost of my answer to a similar question related to sets.)
One way is to use reduce
with lambda x: x
.
from functools import reduce
> reduce(lambda x: x, [3]})
3
> reduce(lambda x: x, [1, 2, 3])
TypeError: <lambda>() takes 1 positional argument but 2 were given
> reduce(lambda x: x, [])
TypeError: reduce() of empty sequence with no initial value
Benefits:
Cons: "API misuse" (see comments).
lambda
, you could literally pass any function accepting any number of arguments aside from two (e.g. ord
, lambda: None
, etc.), and get the same result. It "works" because the function is never even called when there is only one thing in the input, and if it's called, it dies immediately. You may as well simplify it by just letting function call syntax do the job, as in my rampant insanity version ((lambda x: x)(*mylist)
), with the same benefits.
May 1, 2022 at 22:02
iter
because the language did it implicitly for you (the same way it does for unpacking, use of for
loops, etc.).
May 1, 2022 at 22:06
list
is not the best data type?mylist[0]
succeeds when you have at least one element, but doesn't complain if you actually had 30 elements.singleitem, = mylist
verifies that you've got exactly one element, no more, no less.