Monday, 12 October 2020

Unpacking multiple lists and dictionaries as function arguments in Python 2

Possible Relevant Questions (I searched for the same question and couldn't find it)


Python makes a convenient way to unpack arguments into functions using an asterisk, as explained in https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In my code, I'm calling a function like this:

def func(*args):
    for arg in args:
        print(arg)

In Python 3, I call it like this:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

func(*a, *b, *c)

Which outputs

1 2 3 4 5 6 7 8 9

In Python 2, however, I encounter an exception:

>>> func(*a, *b, *c)
  File "<stdin>", line 1
    func(*a, *b, *c)
             ^
SyntaxError: invalid syntax
>>> 

It seems like Python 2 can't handle unpacking multiple lists. Is there a better and cleaner way to do this than

func(a[0], a[1], a[2], b[0], b[1], b[2], ...)

My first thought was I could concatenate the lists into one list and unpack it, but I was wondering if there was a better solution (or something that I don't understand).

d = a + b + c
func(*d)


from Unpacking multiple lists and dictionaries as function arguments in Python 2

No comments:

Post a Comment