What are *args and **kwargs in Python

Python May 19, 2023

The special syntax *args and **kwargs in function definitions is used to pass a variable number of arguments to a function. Let's break each of them down:
Positional Arguments (*args)

The *args syntax in a function signature is used to pass a variable-length list of positional arguments. The single asterisk (*) before the variable name (args is a naming convention, but you can use any name you want) collects multiple positional arguments into a single tuple.

Here's a simple example:

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3, 4))  # Output: 10

In this example, *args collects the arguments 1, 2, 3, and 4 into a tuple (1, 2, 3, 4), and then the sum function calculates their sum.

Keyword Arguments (**kwargs)

The **kwargs syntax is similar to *args, but instead of collecting positional arguments, it collects keyword (named) arguments into a dictionary. The double asterisks (**) before the variable name (again, kwargs is a naming convention) signal that any extra named arguments passed to the function should be gathered into a dictionary.

Here's an example:

def print_data(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_data(name="Alice", age=30, country="USA")

Output:

name: Alice
age: 30
country: USA

In this example, **kwargs collects the keyword arguments name="Alice", age=30, country="USA" into a dictionary {'name': 'Alice', 'age': 30, 'country': 'USA'}, and then the function iterates through the dictionary to print out the data.

Using *args and **kwargs Together

You can use both *args and **kwargs in a function definition, but *args has to appear before **kwargs.

def func(a, b, *args, keyword1=None, **kwargs):
    print(a, b)
    print(args)
    print(keyword1)
    print(kwargs)

func(1, 2, 3, 4, 5, keyword1="hello", keyword2="world")

 OUTPUT:

1 2
(3, 4, 5)
hello
{'keyword2': 'world'}

In this example, a and b are standard positional arguments, *args collects extra positional arguments, keyword1 is a standard keyword argument, and **kwargs collects additional keyword arguments.

Understanding *args and **kwargs is crucial for writing flexible functions that can handle a variety of input, and they're also commonly used in class method overrides, decorators, and other advanced Python features.

Tags