3 ms·
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 varia
by Goladus 16y ago
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)
- cool-RR 16y agoI 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 :)
- masklinn 16y agoThat'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.
- Goladus 16y agoI 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.
- jedbrown 16y agoreturn reduce(fn, lst) does the same thing.