Reputation: 51
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)
Upvotes: 5
Views: 1653
Reputation: 24134
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.
*args
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)
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))
1
2
3
4
5
6
7
8
9
**kwargs
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)
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())))
Upvotes: 13