121

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.

7
  • 5
    There may be alternatives, but there's usually only one obvious way to do it - and, in this case, you seem to have already found it.
    – ekhumoro
    Oct 16, 2015 at 2:23
  • 1
    if it always contains a single item, then maybe a list is not the best data type? Oct 16, 2015 at 2:24
  • 19
    @ekhumoro: I'm actually partial to the sequence unpacking method, because it verifies the assumption that the sequence only has one element. 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. Oct 16, 2015 at 2:27
  • 1
    @ShadowRanger. The question is explicitly about accessing the only element in a list which is already known to contain a single item.
    – ekhumoro
    Oct 16, 2015 at 2:34
  • 11
    @ekhumoro: No disagreement. I just prefer to program defensively, so violations of requirements don't pass silently (sure it fails, but it fails loudly, which is much easier to identify and fix than subtle misbehaviors). If I had a nickel for every time some "known" behavior in production code turned out to be dead wrong... Well, I probably wouldn't be rich, but I'd be able to take the family out to a really nice dinner. Oct 16, 2015 at 2:38

3 Answers 3

176

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

Rampant insanity, unpack the input to the identity 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)

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

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

22
  • 8
    The first one is unique in that it also raises if the list contains more than one element.
    – Neil G
    Oct 16, 2015 at 9:40
  • 9
    The first can also be written as [singleitem] = mylist.
    – Carsten S
    Oct 16, 2015 at 10:00
  • 1
    @CarstenS: Usually, I frown on using [] 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
  • 1
    @Bharel: Okay, so as long as we're agreed that's batshit insane, we're good. :-) Sep 23, 2016 at 23:15
  • 1
    @DavidWaterworth: That silences the exception you'd get for passing a sequence with >1 item by silently collecting all the other items into _ (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
24

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

2
  • Back when you wrote this answer, 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
  • In particular, the new code is slower by the greatest margin for the success case (which is presumably the common case); in 3.11.1, the original implementation takes around 41 ns on a one-tuple on my machine, while the new one takes 348 ns. It's slower in the failure cases too (particularly when the iterable is too long), but those hardly matter (and the relative loss is much smaller, taking only 25-100% longer, not ~9x). Jan 20 at 19:35
0

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

  • Fails for multiple and zero values
  • Doesn't change the original list
  • Doesn't need a new variable and can be passed as an argument

Cons: "API misuse" (see comments).

3
  • This is stacking a lot of random garbage to get a result through, essentially, API misuse. It isn't gaining any benefit unique to the 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
  • 1
    To be clear, I enjoy stupid new ways to do simple things. I just don't support a claim that importing a function, and intentionally misusing it to get a benefit by side-effect from the misuse, is "Arguably less awkward and PEP-compliant" than literally any other solution out there. Also, just to be clear, this solution does involve transforming to an iterable; you don't see a call to 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
  • @ShadowRanger Thanks for the feedback. I adjusted the post base on them.
    – nocibambi
    May 2, 2022 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.