Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator.itemgetter or lambda

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?

like image 808
Endophage Avatar asked Jun 21 '13 20:06

Endophage


People also ask

What is operator Itemgetter?

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.

What is key Itemgetter in Python?

itemgetter() for the key parameter. itemgetter() in the standard library operator returns a callable object that fetches a list element or dictionary value.

How does operator Itemgetter work?

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.

What does Attrgetter do Python?

attrgetter(attribute) or operator. attrgetter(*attribute) returns a callable object that fetches attribute from it's operand.


1 Answers

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 
like image 114
michaelmeyer Avatar answered Sep 21 '22 05:09

michaelmeyer