What is Variable-Length Positional Arguments (*args) in python?
In Python, Variable-Length Positional Arguments (often referred to as *args
) allow a function to accept an arbitrary number of positional arguments. This makes the function flexible to handle cases where the number of inputs isn’t fixed or known beforehand.
The *
symbol before args
tells Python to gather any extra positional arguments into a tuple named args
.
You can then iterate over or process args
as needed, since it behaves like any other tuple.
Why Use *args
?
- Flexibility: It allows a function to handle an unknown number of arguments, making it more adaptable.
- Conciseness: You don’t need to define multiple parameters if you’re unsure how many arguments you’ll receive.
def print_all(*args):
for arg in args:
print(arg)
print_all("apple", "banana", "cherry")
# Output:
# apple
# banana
# cherry
Common Scenarios for *args
1. Summing Multiple Numbers
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4)) # Output: 10
print(add_numbers(10, 20)) # Output: 30
2. Combine Strings
def combine_strings(*args):
return " ".join(args)
# Example usage
print(combine_strings("Hello", "world", "from", "Python"))
# Output: Hello world from Python
3. Passing a Variable List of Names to Greet
def greet_people(greeting, *names):
for name in names:
print(f"{greeting}, {name}!")
greet_people("Hello", "Alice", "Bob", "Charlie")
# Output:
# Hello, Alice!
# Hello, Bob!
# Hello, Charlie!
4. Combining Lists
def combine_lists(*args):
combined = []
for lst in args:
combined.extend(lst)
return combined
print(combine_lists([1, 2], [3, 4], [5, 6])) # Output: [1, 2, 3, 4, 5, 6]
Combining *args
with Other Parameter Types
You can mix *args
with other parameters, allowing you to enforce certain required arguments while accepting an arbitrary number of additional ones. The order in function definition is as follows:
- Regular positional arguments
*args
for variable-length positional arguments**kwargs
for variable-length keyword arguments (if needed)
def example_function(required, *args, **kwargs):
print("Required:", required)
print("Args:", args)
print("Kwargs:", kwargs)
example_function("Must have this", "extra1", "extra2", key1="value1", key2="value2")
# Output:
# Required: Must have this
# Args: ('extra1', 'extra2')
# Kwargs: {'key1': 'value1', 'key2': 'value2'}
Answers generated by OpenAI's ChatGPT with some editing.