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 is a built-in module providing a set of convenient operators. In two words operator. itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
itemgetter() for the key parameter. itemgetter() in the standard library operator returns a callable object that fetches a list element or dictionary value.
operator. itemgetter() that fetches an “item” using the operand's __getitem__() method. If multiple values are returned, the function returns them in a tuple. This function works with Python dictionaries, strings, lists, and tuples.
attrgetter(attribute) or operator. attrgetter(*attribute) returns a callable object that fetches attribute from it's operand.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With