4 ms·
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 u
by teilo 16y ago
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.
- jemfinch 16y agoThe 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.
- cturner 16y agoWhat 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.
- dochtman 16y agoWe also commonly use tuples as light-weight types (a kind of heterogeneous collection).
- njharman 16y agoLists use (not infrequently) logic like the following; If one element do this one element thing else do this more than one element thing
- iron_ball 16y agoBut 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.
- teilo 16y agoThat 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.
- baddox 16y agoDjango's ORM, the only Python one I've experience with, provides get() for those cases.