Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python operator.itemgetter work given a comma separated list of numbers as indices, but not when the same list is packaged in a variable?

Tags:

python

Here is a demonstration of the issue I'm having. I'm fairly new to Python, so I'm pretty sure I'm overlooking something very obvious.

import operator

lista=["a","b","c","d","e","f"]
print operator.itemgetter(1,3,5)(lista)
>> ('b', 'd', 'f')

columns=1,3,5
print operator.itemgetter(columns)(lista)
>> TypeError: list indices must be integers, not tuple

How do I get around this issue so I can use an arbitrary list of indices specified as an argument at program start?

like image 629
user2066631 Avatar asked Jul 17 '13 22:07

user2066631


People also ask

How does Itemgetter work 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. You sort a two-dimensional list according to the value of any position (index) with operator.

What is the use of Itemgetter?

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. So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

What is Attrgetter Python?

attrgetter (attr) operator. attrgetter (*attrs) Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes.


2 Answers

This isn't about itemgetter, but about function calling syntax. These are different things:

operator.itemgetter(1, 3, 5)

operator.itemgetter((1, 3, 5))

The first one gets you item #1, item #3, and item #5. The second one gets you item #(1, 3, 5). (Which may make sense for a dictionary, but not for a list.)

The second one is what you get when you use itemgetter(columns). So, how do you get the first?

operator.itemgetter(*columns)

That's it.

See Unpacking Argument Lists in the tutorial for more information.

like image 198
abarnert Avatar answered Oct 19 '22 16:10

abarnert


You need to pass individual arguments to itemgetter. columns here is a tuple (1, 3, 5) You can use the * operator to unpack it in the function call. The * expands a list or tuple so that its values are sent as individual arguments, rather than passing the entire tuple as one argument.

For example: func(*(1, 2, 3)) == func(1, 2, 3)

so what you need is:

columns=1,3,5
print operator.itemgetter(*columns)(lista)
like image 27
Ryan Haining Avatar answered Oct 19 '22 17:10

Ryan Haining