4 ms·
Also, wouldn't the existence of a library function (#3) imply that what you're doing is either non-trivial or common enough that someone has already given the f
by ndpi 8y ago
Also, wouldn't the existence of a library function (#3) imply that what you're doing is either non-trivial or common enough that someone has already given the function a name? Seems like #1 is sufficient.
- eesmith 8y agoTo give an example based on the article, I find it cumbersome to use itemgetter. I could use the library function: import operator sort(values, key=operator.itemgetter(2)) but it seems decidedly trivial and common to use a lambda: sort(values, key=lambda x: x[2])
- tomnipotent 8y agoThe first returns a callable, the second a value.
- codebje 8y agoThe first returns a callable that's the value assigned to the key argument. The second is a callable that's the value assigned to the key argument. They're the same thing.
- dpwm 8y agoThe risk of identifier collisions with itemgetter seems really low. I've never had a problem with from operator import itemgetter sort(values, key=itemgetter(2)) The main problem is the effort of typing the import, but last time I checked itemgetter performed a bit better. To me it depends on what I'm writing. If it's a library where performance will matter then it's the itemgetter approach. If it's a script it will be the lambda.