Pyderman Pyderman - 1 year ago 64
Python Question

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

When a Python list is known to always contain a single item, is there way to access it other than:


You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.

Answer Source

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

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

Many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download