I often forget it, so make a note.
If * args
is specified as an argument, it will receive an arbitrary number of arguments and become a tuple.
>>> def func(a, b, *args):
... print('a: {}'.format(a))
... print('b: {}'.format(b))
... print('*args: {}'.format(args))
...
>>> func(1, 2, 3, 4, 5, 6)
a: 1
b: 2
*args: (3, 4, 5, 6)
If ** kargs
is specified as an argument, it will receive an arbitrary number of keyword arguments and become a dictionary.
>>> def func(a, b, **kargs):
... print('a: {}'.format(a))
... print('b: {}'.format(b))
... print('**kargs: {}'.format(kargs))
...
>>> func(1, 2, x=3, y=4, z=5)
a: 1
b: 2
**kargs: {'z': 5, 'x': 3, 'y': 4}
If you add *
to the list and pass it as an argument, it will be unpacked and assigned to the argument.
>>> args = [1, 2, 3]
>>> def func(a, b, c):
... return a + b + c
...
>>> func(*args)
6
If you add **
to the dictionary and pass it to the argument, it will be unpacked and assigned to the argument.
>>> kargs = {'a': 3, 'b': 4, 'c': 5}
>>> def func(a, b, c):
... return a + b + c
...
>>> func(**kargs)
12
>>> args = [3, 4, 5]
>>> def func(a, b, *args):
... print('a: {}'.format(a))
... print('b: {}'.format(b))
... print('*args: {}'.format(args))
...
>>> func(1, 2, *args)
a: 1
b: 2
*args: (3, 4, 5)
It is unpacked by passing it as an argument with * args
, and the function receives it as a variadic argument, so it becomes a list.
It's a story that you can give it as a list from the beginning, but you can also do this.
Recommended Posts