Practical Examples of *args
Summing Numbers
One common use case for *args
is to write a function that can sum up any number of arguments.
def sum_numbers(*args):
total = 0
for num in args:
total += num
return total
print(sum_numbers(1, 2, 3)) ## Output: 6
print(sum_numbers(4, 5, 6, 7, 8)) ## Output: 30
print(sum_numbers()) ## Output: 0
In this example, the sum_numbers()
function uses *args
to accept any number of arguments, which are then summed up and returned.
Printing Variable-Length Arguments
Another example is a function that can print any number of arguments.
def print_args(*args):
for arg in args:
print(arg)
print_args(1, 2, 3)
## Output:
## 1
## 2
## 3
print_args('a', 'b', 'c', 'd')
## Output:
## a
## b
## c
## d
In this case, the print_args()
function uses *args
to accept a variable number of arguments, which are then printed one by one.
Collecting Keyword Arguments with **kwargs
In addition to *args
, Python also supports the **kwargs
syntax, which allows you to collect keyword arguments (key-value pairs) into a dictionary.
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_kwargs(name="LabEx", age=30, city="New York")
## Output:
## name: LabEx
## age: 30
## city: New York
In this example, the print_kwargs()
function uses **kwargs
to collect any number of keyword arguments, which are then printed as key-value pairs.
By combining *args
and **kwargs
, you can create highly flexible and powerful functions that can handle a wide range of input scenarios.
graph TD
A[Function Definition] --> B(*args, **kwargs)
B(*args, **kwargs) --> C[Tuple of Positional Arguments]
B(*args, **kwargs) --> D[Dictionary of Keyword Arguments]
C[Tuple of Positional Arguments] --> E[Function Body]
D[Dictionary of Keyword Arguments] --> E[Function Body]
These practical examples demonstrate how you can leverage the *args
syntax to write more versatile and reusable Python functions. By understanding and applying these techniques, you can create functions that are better equipped to handle a variety of use cases.