Understanding and Using Variable-Length Arguments
Variable-length arguments
, also known as varargs
, are a feature in functions that allow you to pass an arbitrary number of arguments without having to predefine their number.
Variable arguments can be used in the function's parameters by prefixing them with *
for positional arguments or **
for keyword arguments.
*
accepts an arbitrary number of positional arguments, whereas **
accepts an arbitrary number of keyword argument pairs.
*args
Syntax
In Python, *args
is used to pass a variable number of positional arguments to a function when the number of arguments isn't predetermined.
By prefixing the parameter with *
, the function processes these arguments as a tuple internally.
def print_numbers(*numbers):
for number in numbers:
print(number)
print_numbers(1, 2, 3)
# Output: 1, 2, 3
**kwargs
Syntax
**kwargs
allows passing a variable number of keyword arguments to a function.
By prefixing the parameter with **
, the function processes these arguments as a dictionary internally.
def print_numbers(**numbers):
for key, value in numbers.items():
print(f'{key}: {value}')
print_numbers(first=1, second=2, third=3)
# Output: first: 1, second: 2, third: 3
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.