*args and **kwargs
Table of contents:
*args and **kwargs
*args and **kwargs allow user to pass multiple arguments(args) and keyward arguments(kwargs) to a function. *args can unpack iterable and **kwargs is for unpacking dictionaries.
*args
When we declare a function to sum up numbers, we often need to pass arguments. There are several ways to do so. The most common method is using a sigle list as the function argument. However, using *args as the alternative method can make the code elegant.
The first example using list as the argument::
15
Using *args instead of a list:
- It can takes multiple arguments.
15
List unpacking
The idea of unpacking is to, well, unpack any iterable object. The single asterisk *
is used to unpack any iterable.
1 2 3 4 5
The result above shows that the print function can print the element of the list by using *args
List concatenation
Another thing that *args can do is list concatenation:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
**kwargs
**kwargs
are used to unpack dictionaries.
Let’s try a calculation function that take a, b and c using traditional positional arguments:
122
However, if we use the **kwargs
, we can get the same results.
122
It is clear to see that using **kwargs
is simpler, cleaner and more elegant.
Dictionary concatenation
The dictionary concatenation is the same as the list concatenation. It will concatenate two different dictionaries into one. But, if there are duplicate keys, the value of the second dictionary will be used.
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
The key b has the value of 2
.
{'a': 1, 'b': 3, 'c': 4}
Now, the key b has the value of 3
.