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?

python

Solution

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.

Problem

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?

Original source