Predictive Hacks

Example of args and kwargs in Python

With args, we can pass in any amount of non-keyword variables, while with kwargs we can pass in any amount of keyword arguments. We will explain the args and kwargs using an example of a sum function. More particularly, assume that we would like to build a function that sums up a list of numbers, without knowing the exact number of inputs.

Example of args

We will build a function called sum_func that can take any number of arguments and the total sum will be returned.

def sum_func(*args):
    my_sum = 0
    for n in args:
        my_sum+=n
    return(my_sum)

print(sum_func(1,2,3,4))
10

As we can see, we passed the arguments “1,2,3,4” and it returned correctly 10 since 1+2+3+4 = 10.

Example of kwargs

Assume that we would like to sum the values based on the key values. For example, let’s say that we want to sum up incomes with the expenses (negative values). Using kwargs we iterate over a dictionary. In the example below, for every key (k), we add up its corresponding value (v).

def sum_func(**kwargs):
    my_sum = 0
    for k, v in kwargs.items():
        my_sum+=v
    return(my_sum)

print(sum_func(salary=1000, rent=-300))
 
700

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.