Getting only element from a single-element list in Python? Getting only element from a single-element list in Python? python python

Getting only element from a single-element list in Python?


Raises exception if not exactly one item:

Sequence unpacking:

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

All others silently ignore spec violation, producing first or last item:

Explicit use of iterator protocol:

singleitem = next(iter(mylist))

Destructive pop:

singleitem = mylist.pop()

Negative index:

singleitem = mylist[-1]

Set via single iteration for (because the loop variable remains available with its last value when a loop terminates):

for singleitem in mylist: break

Rampant insanity:

# But also the only 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 worksingleitem = (lambda x: x)(*mylist)

There are 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_itertoolslibrary has a tool that returns one item from an iterable.

from more_itertools import oneiterable = ["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