Live data from Hacker News

Python idiom for taking the single item from a list

blog.garlicsim.org

1–10 of 97 posts

Re: Python idiom for taking the single item from a list

#4
post #3

Very good idea, I support this and will use it from now on (even though I don't like the (thing,) Python syntax very much), as it's the only way to say that the iterable should only have one element.

As a commenter there noted,

[thing] = stuff

works too. I think I like that even better.

Re: Python idiom for taking the single item from a list

#6
So we have

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.

and then later on,

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.

The second argument is basically in favor of duck-typing which is the pythonic way of writing code, ie, not caring about the actual object but only if it responds to the given message.

But what about the first argument? Couldn't you make the case that the pythonic way of handling it is to only care about if the object responds to __getitem__(0)?

Which idiom you use would depend entirely on context, wouldn't it?

Re: Python idiom for taking the single item from a list

#8
My problem is that exact situation almost never comes up. Usually, I want to use the item in the list directly in an expression, not assign it to another variable first. For example:

    if 1==len(lst):
        return lst[0]
    else:
        return reduce(fn, lst)
I don't really want to have to do:

    if 1==len(lst):
        (single,)=lst
        return single
    else:
        return reduce(fn, lst)
Post reply on HN