2

The General Question

What is the python3.5+ syntax for calling a function that accepts *args, where *args references a variable with multiple items.

I am self taught python; I can't help but think I am missing something rather elementary about how *args works. Feel free to point me to some necessary reading.

A Specific Question

When sorting a list of lists by columns using operator.itemgetter(*items), how can I provide *items variably?

Sample List

import operator

records = [
    ['0055613893 ', 'AP', 'BU', 'AA', '00005000012404R'],
    ['0048303110 ', 'MM', 'BU', 'AB', '00028230031385R'],
    ['0044285346 ', 'AP', 'BU', 'AA', '00062240050078R'],
    ['0048303108 ', 'MO', 'BU', 'AF', '00047780036604R'],
    ['0048751228 ', 'AP', 'ME', 'AC', '00000750013177R'],
    ['0045059521 ', 'AR', 'YT', 'AB', '00005430014570R']
]

If I wanted to sort this particular recordset by the 3rd column and then by the 1st column I would:

records.sort(key=operator.itemgetter(3, 1))

This, of course, works as one would expect.

What I'm getting at is how can I provide the "3, 1" to itemgetter() variably?

i.e.:

indices = {insert some code here to provide itemgetter() what it needs} records.sort(key=operator.itemgetter(indices))

I've Tried:

tuple:

indices = (3, 1) or indices = 3, 1

TypeError: list indices must be integers or slices, not tuple

list:

indices = [3, 1]

TypeError: list indices must be integers or slices, not list

It's never too late to be humbled by the basics. Thanks in advance for assisting in filling this gap in my python foundation.

DRH
  • 7,868
  • 35
  • 42
JerodG
  • 1,248
  • 1
  • 16
  • 34

1 Answers1

1

Let's say you have

indices = [3, 1]

The you can use Python unpacking to give 3 and 1 to function calls:

itemgetter(*indices)

This is equivalent to

itemgetter(3, 1)

I'm not sure what versions of Python this works on. This is one of the rapidly changing parts, so you might have to do a little reading if you're using an old version.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96