News for hackers. Stuff that matters.
Re:Python idiom for taking the single item from a list by teilo on Monday September 27, 2010 @12:47PM (#1732290)
Excellent. That one belongs in any Python style guide. Though technically it's not a style, it does lead to better readability, and reduces the propensity for unforseen consequences.
Re:Python idiom for taking the single item from a list by jemfinch on Monday September 27, 2010 @02:50PM (#1732858)
The reason it's not in the Python style guide is because it's a symptom of other problems in code. Lists are for holding multiple values of the same type. If you know that a list will always have one and only one value, it's not conceptually a list, it's some other type that's been encoded into a list for some reason, and you should fix that conceptual mismatch rather than papering over the issue with a style idiom.
Re:Python idiom for taking the single item from a list by teilo on Monday September 27, 2010 @06:37PM (#1733779)
That sounds logical enough, except for two things:

First: You are often working with someone-else's library which for various reasons you cannot change.

Second: It is not uncommon to use a standard method that may well be able to return multiple items, but in your use case it should only return one. Case in point: a database call that returns the result of a query.

Re:Python idiom for taking the single item from a list by baddox on Monday September 27, 2010 @08:14PM (#1734076)
Django's ORM, the only Python one I've experience with, provides get() for those cases.
Re:Python idiom for taking the single item from a list by dochtman on Monday September 27, 2010 @03:15PM (#1732957)
We also commonly use tuples as light-weight types (a kind of heterogeneous collection).
Re:Python idiom for taking the single item from a list by cturner on Tuesday September 28, 2010 @02:30AM (#1734784)
What you say sounds right, but it's not. Using some DB APIs you'll get back a list of results, and you'll know from the SQL that it will only have one result.

Another example is if you know there is a single item in a data structure, and use list comprehension to extract it. You'll end up with a list of one item.

These situations happen, and for good reasons.

Re:Python idiom for taking the single item from a list by njharman on Monday September 27, 2010 @04:29PM (#1733267)
Lists use (not infrequently) logic like the following;

  If one element
    do this one element thing
  else
    do this more than one element thing
Re:Python idiom for taking the single item from a list by iron_ball on Monday September 27, 2010 @04:54PM (#1733373)
But in that case, either your code is evidently in a branch where the list will have one item -- as in your example -- in which case the context makes it clear. And if there's no context, such as in a nested function call, then at some point you should be passing that lone list item into a function which takes the item as an argument.