Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 625
NoNo EsImposible Avatar asked Oct 26 '18 03:10

NoNo EsImposible


People also ask

How do you pass a list of arguments to a function in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

What is dictionary unpacking in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .

Can we do unpacking of list in Python?

We can use * to unpack the list so that all elements of it can be passed as different parameters.

How do you pass multiple dictionary parameters in Python?

**kwargs: Pass multiple arguments to a function in Python If so, use **kwargs . **kwargs allow you to pass multiple arguments to a function using a dictionary. In the example below, passing **{'a':1, 'b':2} to the function is similar to passing a=1, b=1 to the function.


1 Answers

Recommendation: Migrate to Python 3
As of January 1, 2020, the 2.x branch of the Python programming language is no longer supported by the Python Software Foundation.

Unpacking Lists and passing to *args

Python 3 Solution

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

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

func(*a, *b, *c)

Python 2 Solution

If Python 2 is required, then itertools.chain will provide a workaround:

import itertools


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

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

func(*itertools.chain(a, b, c))

Output

1
2
3
4
5
6
7
8
9

Unpacking Dictionaries and passing to **kwargs

Python 3 Solution

def func(**args):
    for k, v in args.items():
        print(f"key: {k}, value: {v}")


a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}

func(**a, **b, **c)

Python 2 Solution

As Elliot mentioned in the comments, if you need to unpack multiple dictionaries and pass to kwargs, you can use the below:

import itertools

def func(**args):
    for k, v in args.items():
        print("key: {0}, value: {1}".format(k, v))


a = {"1": "one", "2": "two", "3": "three"}
b = {"4": "four", "5": "five", "6": "six"}
c = {"7": "seven", "8": "eight", "9": "nine"}

func(**dict(itertools.chain(a.items(), b.items(), c.items())))
like image 59
Christopher Peisert Avatar answered Oct 18 '22 19:10

Christopher Peisert