News for hackers. Stuff that matters.
Re:Python idiom for taking the single item from a list by Goladus on Monday September 27, 2010 @01:42PM (#1732507)
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)
Re:Python idiom for taking the single item from a list by cool-RR on Monday September 27, 2010 @01:52PM (#1732564)
I see what you mean. In this case it's indeed questionable whether this idiom would improve the code. The only improvement I can offer for this code is to fix the Yoda conditions :)
Re:Python idiom for taking the single item from a list by masklinn on Monday September 27, 2010 @01:57PM (#1732587)
That's very different than OP's piece of code: you're not trying to assert that the iterable yields a single element, you already know it.

Furthermore, OP's assertion-unpacking will work not just on lists, but also on dicts (will return the only key, not the only value, and the key doesn't have to be ``0``), on sets (which don't implement __getitem__ at all), on arbitrary collections and even on arbitrary iterables (including callable_iterator and generators)

Also, please don't put the constant on the left-hand of a comparison in Python, it's useless and ugly.

Re:Python idiom for taking the single item from a list by Goladus on Monday September 27, 2010 @02:13PM (#1732684)
I agree it's cool that it works on lists and sets and dictionary keys. Upvoted, etc. Just noting that there are many situations where it won't replace the [0].

Also, I don't worry about order on simple equality expressions unless someone asks me to do it a certain way. That's a religious argument and a complete waste of time for me.

Re:Python idiom for taking the single item from a list by jedbrown on Monday September 27, 2010 @02:25PM (#1732748)

  return reduce(fn, lst)
does the same thing.