Home Picture

Python Baisc: *args and **kwargs

15 Aug 2020 |

Categories: Python

*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::

def sum_num(list_num):
    total=0
    for n in list_num:
        total += n
    return total

numbers = [1, 2, 3, 4, 5]
sum_num(numbers)
15

Using *args instead of a list:

def sum_num_args(*args):
    total=0
    for n in args:
        total += n
    return total

sum_num_args(1, 2, 3, 4, 5)
sum_num_args(1, 2, 3, 4, 5)
15

List unpacking

The idea of unpacking is to, well, unpack any iterable object. The single asterisk * is used to unpack any iterable.

num_arr = [1, 2, 3, 4, 5]
print(*num_arr)
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:

nums1 = [1, 2, 3, 4, 5, 6]
nums2 = [7, 8, 9, 10]
nums = [*nums1, *nums2]
print(nums)
[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:

dic={'a':1 , 'b':20, 'c':12}
def calculate(a, b, c):
    total = a*10 + b*5 + c*1
    return total

calculate(dic['a'], dic['b'], dic['c'])
122

However, if we use the **kwargs, we can get the same results.

calculate(**dic)
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.

# No key duplication
dic1 = {'a': 1, 'b': 2}
dic2 = {'c': 3, 'd': 4}
d = {**dic1, **dic2}
print(d)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

The key b has the value of 2.

# key duplication
dic1 = {'a': 1, 'b': 2}
dic2 = {'b': 3, 'c': 4}
d = {**dic1, **dic2}
print(d)
{'a': 1, 'b': 3, 'c': 4}

Now, the key b has the value of 3.

Top