In Python, *args
**kwargs
Arbitrary positional arguments (args)
The *args
Example 1: Printing positional arguments
def my_function(*args):
for arg in args:
print(arg)
How it works:
collects all positional arguments passed to the function and stores them as a tuple.*args - You can loop through the tuple to access each argument.
Calling the function:
my_function(1, 2, 3)
# Output:
# 1
# 2
# 3
my_function("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry
Example 2: Summing numbers with *args
Suppose you want to create a function that sums any number of arguments:
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3)) # Output: 6
print(sum_numbers(10, 20, 30, 40)) # Output: 100
How it works:
allows the function to handle any number of numerical arguments, making it adaptable to different inputs.
Arbitrary keyword arguments (kwargs)
The **kwargs
Example 1: Printing keyword arguments
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
How it works:
collects keyword arguments as a dictionary.**kwargs - You can access each key-value pair in the dictionary.
Calling the function:
my_function(name="Alice", age=30, city="Paris")
# Output:
# name: Alice
# age: 30
# city: Paris
Example 2: Building a user profile with **kwargs
Let's create a function that accepts any number of user attributes and builds a profile.
def build_profile(**kwargs):
profile = {}
for key, value in kwargs.items():
profile[key] = value
return profile
user_profile = build_profile(name="Alice", age=30, job="Engineer")
print(user_profile) # Output: {'name': 'Alice', 'age': 30, 'job': 'Engineer'}
How it works:
- The function accepts any number of keyword arguments and stores them in a dictionary.
- It allows for flexibility, as it can handle different or optional attributes.
Combining *args and kwargs
You can use both *args
**kwargs
*args
**kwargs
Example: Displaying information from both *args and **kwargs
def display_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
display_info(1, 2, 3, name="Alice", age=30)
# Output:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 30}
How it works:
- The
parameter captures all positional arguments as a tuple.*args
- The
parameter collects keyword arguments as a dictionary.**kwargs
- Both are printed separately, allowing the function to handle a mix of argument types.
Summary
allows for a flexible number of positional arguments, accessible as a tuple.*args
enables you to pass a variable number of keyword arguments, accessible as a dictionary.**kwargs - You can combine both in a function to handle a wide range of arguments (positional and keyword).
These tools offer great flexibility in Python, making your functions more adaptable and scalable. You can use them to write functions that can accept a dynamic number of inputs, making your code cleaner and more reusable.