Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use operator.itemgetter(x) instead of [x]?

There is a more general question here: In what situation should the built-in operator module be used in python?

The top answer claims that operator.itemgetter(x) is "neater" than, presumably, than lambda a: a[x]. I feel the opposite is true.

Are there any other benefits, like performance?

like image 985
thebossman Avatar asked Jul 02 '12 02:07

thebossman


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.


3 Answers

You shouldn't worry about performance unless your code is in a tight inner loop, and is actually a performance problem. Instead, use code that best expresses your intent. Some people like lambdas, some like itemgetter. Sometimes it's just a matter of taste.

itemgetter is more powerful, for example, if you need to get a number of elements at once. For example:

operator.itemgetter(1,3,5) 

is the same as:

lambda s: (s[1], s[3], s[5]) 
like image 69
Ned Batchelder Avatar answered Sep 28 '22 17:09

Ned Batchelder


There are benefits in some situations, here is a good example.

>>> data = [('a',3),('b',2),('c',1)]
>>> from operator import itemgetter
>>> sorted(data, key=itemgetter(1))
[('c', 1), ('b', 2), ('a', 3)]

This use of itemgetter is great because it makes everything clear while also being faster as all operations are kept on the C side.

>>> sorted(data, key=lambda x:x[1])
[('c', 1), ('b', 2), ('a', 3)]

Using a lambda is not as clear, it is also slower and it is preferred not to use lambda unless you have to. Eg. list comprehensions are preferred over using map with a lambda.

like image 37
jamylak Avatar answered Sep 28 '22 18:09

jamylak


Performance. It can make a big difference. In the right circumstances, you can get a bunch of stuff done at the C level by using itemgetter.

I think the claim of what is clearer really depends on which you use most often and would be very subjective

like image 29
John La Rooy Avatar answered Sep 28 '22 17:09

John La Rooy