Variable Arguments
15 min In ProgressLearning Objectives
- Accept any number of positional arguments with *args
- Accept any number of keyword arguments with **kwargs
- Unpack arguments when calling functions
*args for Positional Arguments
Use *args to accept any number of positional arguments as a tuple.
def total(*numbers):
result = 0
for n in numbers:
result += n
return result
print(total(1, 2, 3))
print(total(10, 20))
Course Example: Filtering Arguments
This function prints only non-integer arguments passed to it.
def print_arguments(*args):
for value in args:
if type(value) == int:
continue
print(value)
print_arguments(1, "hello", 2, "world", 3.14)
📝 Exercise: Flexible Average
Write a function average(*numbers) that returns the average of all provided numbers.
code.py
Output