I know what the meaning of an asterisk is in a function definition in Python.
I often, though, see asterisks for calls to functions with parameters like:
def foo(*args, **kwargs):
first_func(args, kwargs)
second_func(*args, **kwargs)
What is the difference between the first and the second function call?
Let
args = [1,2,3]
:func(*args) == func(1,2,3)
- variables are unpacked out of list (or any other sequence type) as parametersfunc(args) == func([1,2,3])
- the list is passedLet
kwargs = dict(a=1,b=2,c=3)
:func(kwargs) == func({'a':1, 'b':2, 'c':3})
- the dict is passedfunc(*kwargs) == func(('a','b','c'))
- tuple of the dict's keys (in random order)func(**kwargs) == func(a=1,b=2,c=3)
- (key, value) are unpacked out of the dict (or any other mapping type) as named parametersThe difference is how the arguments are passed into the called functions. When you use the
*
, the arguments are unpacked (if they're a list or tuple)—otherwise, they're simply passed in as is.Here's an example of the difference:
When I prefixed the argument with
*
, it actually unpacked the list into two separate arguments, which were passed intoadd
asa
andb
. Without it, it simply passed in the list as a single argument.The same is the case for dictionaries and
**
, except they're passed in as named arguments rather than ordered arguments.