3 ms·
A built in a lot of people don’t know is operator.itemgetter and operator.attrgetter they can be used together with functools and itertools for a lot of purpose
by faizshah 5y ago
A built in a lot of people don’t know is operator.itemgetter and operator.attrgetter they can be used together with functools and itertools for a lot of purposes for example you can sort a list of tuples using operator.itemgetter and sort: https://docs.python.org/3/library/operator.html https://docs.python.org/3/library/operator.html
- whalesalad 5y agoWoah the other operators are even more interesting to me. My goto is an in-line lambda to avoid the import but I didn’t realize there were so many operators defined in the stdlib. Thanks for sharing.
- heinrich5991 5y agoHm, I didn't know about those. At first I thought that I'd just replace it with a lambda, but it seems to support looking up multiple elements/members at the same time, so that might come in handy at some point.
- ehsankia 5y agoWhile I do know about those and they are indeed much more pythonic and cleaner, I often end up just using `lambda x: x[1]` instead of `import operator; operator.itemgetter(1)`. For sort, I'll also often do `sorted(mydict, key=mydict.get)` which is again not the most pythonic. I just wish there were nicer ways to do these in the global namespace, but poluting builtins is probably not a great idea either. Maybe `slice.itemgetter` or `object.attrgetter`.