Understanding *args and **kwargs in Python with Beginner-Friendly Examples
In Python, *args and **kwargs are powerful features that let you create flexible functions that can accept a variable number of arguments. These are especially useful when you don't know in advance how many arguments will be passed to your function.
What is *args?
*args allows a function to accept any number of positional arguments. These arguments are stored in a tuple.
Example:
def print_numbers(*args):
for number in args:
print(number)
print_numbers(1, 2, 3, 4, 5)
Output:
1
2
3
4
5
Here, you can pass as many numbers as you want, and they will all be printed. If no arguments are passed, args will simply be an empty tuple.
What is **kwargs?
**kwargs allows a function to accept any number of keyword arguments. These arguments are stored in a dictionary, where the keys are the argument names and the values are their corresponding values.
Example:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
Output:
name: Alice
age: 25
city: New York
Here, you can pass as many key-value pairs as you want. If no keyword arguments are passed, kwargs will simply be an empty dictionary.
Combining *args and **kwargs
You can use both *args and **kwargs in the same function. This allows you to handle both positional and keyword arguments.
Example:
def describe_person(*args, **kwargs):
print("Attributes:")
for arg in args:
print(f"- {arg}")
print("\nDetails:")
for key, value in kwargs.items():
print(f"{key}: {value}")
describe_person("Friendly", "Helpful", name="Bob", age=30, city="Boston")
Output:
Attributes:
- Friendly
- Helpful
Details:
name: Bob
age: 30
city: Boston
Here, *args collects positional arguments (like "Friendly" and "Helpful"), and **kwargs collects keyword arguments (like name="Bob" and age=30).
Simple Rules to Remember
- Use
*argswhen you need to pass a variable number of positional arguments. - Use
**kwargswhen you need to pass a variable number of keyword arguments. - The order in the function signature should always be:
- Regular positional arguments
*args- Default keyword arguments
**kwargs
Practical Examples for Beginners
Example 1: A Function to Add Numbers
def add_numbers(*args):
total = sum(args)
print(f"The sum is: {total}")
add_numbers(1, 2, 3, 4)
add_numbers(10, 20)
Output:
The sum is: 10
The sum is: 30
Example 2: Greeting People by Name
def greet_people(**kwargs):
for name, greeting in kwargs.items():
print(f"{greeting}, {name}!")
greet_people(Alice="Hello", Bob="Hi", Charlie="Hey")
Output:
Hello, Alice!
Hi, Bob!
Hey, Charlie!
Example 3: Combining *args and **kwargs in a Shopping List
def shopping_list(*items, **prices):
print("Items to buy:")
for item in items:
print(f"- {item}")
print("\nPrices:")
for item, price in prices.items():
print(f"{item}: ${price}")
shopping_list("Apples", "Bananas", Apples=2, Bananas=1.5, Oranges=3)
Output:
Items to buy:
- Apples
- Bananas
Prices:
Apples: $2
Bananas: $1.5
Oranges: $3
Conclusion
By using *args and **kwargs, you can make your Python functions more dynamic and flexible. This is especially useful when working on programs where the number of inputs might vary. Start experimenting with these features in small projects, and you'll see how handy they can be!
Top comments (0)