3 ms·
To 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=operato
by eesmith 8y ago
To 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.