*args and **kwargs
- Python course
- Beginner
- Lesson 75/116
- 5 min
Learn flexible parameters with *args and **kwargs.
Variable arguments with *args
With *args you can send any number of positional arguments to a function; they are collected into a tuple:
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20)) # 30The star makes the incoming values collect into a single tuple. This makes the function flexible.
Keyword arguments with **kwargs
With **kwargs, arguments passed as keywords are collected into a dict:
def show(**kwargs):
for k, v in kwargs.items():
print(k, v)
show(name="Alex", age=28)The double star makes the incoming keyword pairs collect into a dictionary. This is handy for optional settings.
*args and **kwargs can be used together; *args first, then **kwargs.
Practice Write a total function with *args
Define a function called total that takes *args and returns sum(args). Assign total(1, 2, 3) to result. Then print print(result).
Starter code
# Define the total functionSample solution
def total(*args):
return sum(args)
result = total(1, 2, 3)
print(result)Expected output
6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the *args parameter
def total(____):
return sum(args)
def total(*args):
return sum(args)
Explanation: *args collects variable arguments into a tuple.
2 What type does *args appear as inside the function?
- Tuple Correct answer
- List
- Dict
- Set
Explanation: *args values are collected into a tuple.
3 Match args and kwargs types
| Term | Meaning |
|---|---|
*args |
Tuple |
**kwargs |
Dict |
star |
Collection sign |
double star |
Dict collection |