Explain *args and **kwargs in Python

Explain *args and **kwargs in Python

In this article, we’re going to talk about what ** (double star/asterisk) and * (star/asterisk) mean when we use them with parameters in Python. We’ll also look at some examples of args and kwargs in Python. Basically, these special symbols allow us to pass a different number of arguments to a function.

There are two Special Symbols

  1. *args (Non-Keyword Arguments)
  2. **kwargs (Keyword Arguments)

What is Python *args?

The special syntax *args in Python functions lets you pass lots of arguments without specifying them all individually. It’s like a magic way to handle a bunch of arguments at once, even if you didn’t plan for them all in advance.

Here’s how it works: you put *args in the parentheses when you define your function. Then, when you call the function, you can pass in as many arguments as you want, and they all get bundled up into this *args thing.

For instance, imagine you want to make a function that multiplies lots of numbers together. Instead of listing all the numbers as separate arguments, you just use *args and Python takes care of the rest.

The cool part is that *args turns into a list-like thing, so you can loop through it, apply functions to it, and do all sorts of other nifty stuff with it. It’s like a flexible container for all those extra arguments you might need.

Example:


def multiply(*args):
result = 1
for num in args:
result *= num
return result
# Testing the multiply function
print(multiply(2, 3)) # Output: 6
print(multiply(4, 5, 6)) # Output: 120
print(multiply(1, 2, 3, 4)) # Output: 24

Output:
6
120
24

Save $100 in the next
5:00 minutes?

Register Here

What is Python **kwargs?

The special **kwargs syntax in Python functions helps us pass a bunch of keyword arguments, meaning arguments that have names associated with them. When we use **kwargs, it’s like we’re saying, “Hey Python, here are some extra arguments, and they all come with names!”

Think of **kwargs as a dictionary where each keyword argument is a key, and the value associated with it is what we pass into the function. This is why when we loop through **kwargs, the order of the arguments doesn’t seem to matter—they’re all just pairs of names and values. It’s a handy way to handle lots of named arguments without having to list them all out in advance.

Example:


def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key} says {value}")
# Testing the greet function
greet(first='Alice', second='Bob')

Output:

first says Alice
second says Bob
Using both *args and **kwargs in Python to call a function:

Example:


def example_function(*args, **kwargs):
"""
This function demonstrates the usage of both *args and **kwargs.
Parameters:
*args (tuple): Variable-length positional arguments.
**kwargs (dict): Variable-length keyword arguments.
"""
print("Positional arguments (*args):")
for arg in args:
print(arg)
print("\nKeyword arguments (**kwargs):")
for key, value in kwargs.items():
print(f"{key} = {value}")
# Calling the example_function with both *args and **kwargs
example_function('Hello', 'world', name='Alice', age=30)

Output:

Positional arguments (*args):
Hello
world
Keyword arguments (**kwargs):
name = Alice
age = 30

Conclusion

In conclusion, the usage of *args and **kwargs in Python offers powerful ways to handle varying numbers of arguments within functions.

*args enables the passing of multiple non-keyword arguments, allowing for flexibility in function calls without needing to specify each argument individually. It collects these arguments into a tuple-like structure, facilitating operations such as iteration and manipulation within the function.

**kwargs facilitates the handling of keyword arguments, essentially creating a dictionary of named parameters and their corresponding values. This simplifies the process of working with a multitude of named arguments, providing a convenient way to manage them within the function.

Save $100 in the next
5:00 minutes?

Register Here