My name is Ram Rachum, and I'm a Python software developer based in Israel.

This is my personal blog. I write about technology, Python, programming and a bunch of other things.

GitHub profile

Personal Website

27th September 2010

Text

Python idiom for taking the single item from a list

It sometimes happens in code that I have a list, let’s call it stuff, and I know for certain that this list contains exactly one item. And I want to get this item and put it in a variable, call it thing. What’s the best way to do this?

In the past I used to do this:

    thing = stuff[0]

But I think that’s not the best idiom. I came up with a better one:

    (thing,) = stuff

Why is this one better?

  1. Readability: It lets the reader know that stuff has exactly one element.

  2. Free assert: It makes Python assert that stuff has exactly one element, so if I was wrong in my original assumption that stuff has exactly one element, Python will shout at me before this will manifest itself as a hard-to-find bug someplace else in the program.

  3. Hard to miss: The previous method had a [0] at the end. Now, that’s easy to notice in a line as short as thing = stuff[0]. But what if the line was something messy like this:

        thing = some_dict[my_object.get_foobar_handler()][0]

    In this case, the [0] at the end is easy to miss, because when casually glancing the code, it might seem connected to that function call or dict lookup. So the reader might miss the fact that we’re taking an item out of a list here. This would be better in this case:

        (thing,) = some_dict[my_object.get_foobar_handler()]

  4. General for any “collection” (Props to Ulrik for noting this): This method works even when stuff is a set or any other kind of collection. stuff[0] wouldn’t work on a set because set doesn’t support access by index number.

Have fun programming!

Comments
All content in this website is copyright © 1986-2011 Ram Rachum.
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License, with attribution to "Ram Rachum at ram.rachum.com" including link to ram.rachum.com.
To view a copy of this license, visit: http://creativecommons.org/licenses/by-sa/3.0/