¡Sorpréndeme!

Lecture 67: What are *args and **kwargs used for in Python functions?

2025-05-21 10 Dailymotion


In Python, *args and **kwargs are used in function definitions to allow a function to accept a variable number of arguments.

*args (Non-Keyword Arguments): It is used to pass a variable number of non-keyworded arguments to a function. These arguments are collected into a tuple within the function.

**kwargs (Keyword Arguments): It is used to pass a variable number of keyword arguments to a function. These arguments are collected into a dictionary within the function, where the keys are the argument names and the values are the argument values.

Python

def example_function(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)

example_function(1, 2, 3, name="Alice", age=30)
# Output:
# Args: (1, 2, 3)
# Kwargs: {'name': 'Alice', 'age': 30}

*args and **kwargs are useful when you don't know in advance how many arguments will be passed to a function, or when you want to create functions that are flexible and can handle different numbers of arguments.