I was curious if there was any indication of which of operator.itemgetter(0) or lambda x:x[0] is better to use, specifically in sorted() as the key keyword argument as that's the use that springs to mind first. Are there any known performance differences? Are there any PEP related preferences or guidance on the matter?
operator.itemgetter(0)
lambda x:x[0]
sorted()
key
The performance of itemgetter is slightly better:
>>> f1 = lambda: sorted(w, key=lambda x: x[1]) >>> f2 = lambda: sorted(w, key=itemgetter(1)) >>> timeit(f1) 21.33667682500527 >>> timeit(f2) 16.99106214600033
1.4m articles
1.4m replys
5 comments
56.9k users