python star sign before list 1

python star sign before list

Inside a function header:

* collects all the positional arguments in a tuple.

** collects all the keyword arguments in a dictionary.

>>> def functionA(*a, **kw):
       print(a)
       print(kw)

>>> functionA(1, 2, 3, 4, 5, 6, a=2, b=3, c=5)
(1, 2, 3, 4, 5, 6)
{'a': 2, 'c': 5, 'b': 3}


In a function call:

* unpacks a list or tuple into position arguments.

** unpacks a dictionary into keyword arguments.
>>> lis=[1, 2, 3, 4]
>>> dic={'a': 10, 'b':20}
>>> functionA(*lis, **dic)  #it is similar to functionA(1, 2, 3, 4, a=10, b=20)
(1, 2, 3, 4)
{'a': 10, 'b': 20}

Here is what the above code is Doing:
1. The functionA is defined with two parameters: *a and **kw.
2. The functionA is called with 6 positional arguments and 3 keyword arguments.
3. The *a collects all the positional arguments in a tuple.
4. The **kw collects all the keyword arguments in a dictionary.
5. The functionA is called with a list and a dictionary.
6. The *lis unpacks the list into position arguments.
7. The **dic unpacks the dictionary into keyword arguments.

Similar Posts