6
Lesson 6
Arbitrary arguments (*args) and keyword arguments (**kwargs)
In Python, *args and **kwargs allow you to write functions that accept a variable number of arguments. They’re useful when you don’t know beforehand how many arguments you want to pass into your function. Let’s break down each of them.
1. Arbitrary positional arguments (*args):
The *args syntax lets you pass a variable number of positional arguments to a function. This means you can pass as many arguments as you like, and they’ll be accessible in the function as a tuple.
1. Arbitrary positional arguments (*args):
The *args syntax lets you pass a variable number of positional arguments to a function. This means you can pass as many arguments as you like, and they’ll be accessible in the function as a tuple.
def my_function(*args): for arg in args: print(arg)
In this example, *args collects all the positional arguments passed to my_function and stores them in a tuple named args.
Calling the function:
my_function(1, 2, 3) # Output: 1 2 3 my_function("apple", "banana", "cherry") # Output: apple banana cherry
Each argument provided is printed on a new line. With *args, you can pass any number of arguments without changing the function definition.
Example: Sum of numbers
Let’s say we want a function that calculates the sum of any number of numbers.
def sum_numbers(*args): return sum(args) print(sum_numbers(1, 2, 3)) # Output: 6 print(sum_numbers(10, 20, 30, 40)) # Output: 100
Here, *args allows the function to accept a different number of arguments each time.
2. Arbitrary keyword arguments (**kwargs):
The **kwargs syntax allows you to pass a variable number of keyword arguments to a function. These arguments are stored in a dictionary, where the keys are the argument names and the values are the argument values.
def my_function(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")
In this example, **kwargs collects all keyword arguments passed to my_function and stores them in a dictionary named kwargs.
Calling the function:
my_function(name="Alice", age=30, city="Paris") # Output: # name: Alice # age: 30 # city: Paris
Each key-value pair provided in the function call is printed on a new line. Using **kwargs allows you to pass a flexible number of keyword arguments without changing the function definition.
Example: Building a Profile
Let’s create a function that builds a user profile with any number of attributes.
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'}
In this example, **kwargs allows the function to create a dictionary with the user’s information, regardless of how many or which details are provided.
3. Combining *args and **kwargs:
You can use both *args and **kwargs in the same function to accept any combination of positional and keyword arguments. When used together, *args must come before **kwargs in the parameter list.
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}
- args will store (1, 2, 3) as a tuple of positional arguments.
- kwargs will store {'name': 'Alice', 'age': 30} as a dictionary of keyword arguments.
Summary:
- *args allows for a variable number of positional arguments, accessible as a tuple.
- **kwargs allows for a variable number of keyword arguments, accessible as a dictionary.
- Use both to create flexible functions that can handle a wide range of argument inputs.
These tools give you great flexibility when designing functions, especially in cases where the number of inputs can vary widely.