*args and kwargs
Computer Science · Python
Question 1 of 10
0What does this Python code print? def count_items(*items): return len(items) print(count_items(3, 7))
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
*args and kwargs explained
A Python function can accept any number of extra arguments by declaring special parameters. A parameter prefixed with one star collects extra positional arguments into a tuple, and a parameter prefixed with two stars collects extra keyword arguments into a dictionary.
In a function definition, a parameter prefixed with one star collects any extra positional arguments into a tuple. The conventional name is args. A parameter prefixed with two stars collects any extra keyword arguments into a dictionary, conventionally named kwargs.
Order matters in the definition: regular parameters come first, then the one-star parameter, then any keyword-only parameters, and finally the two-star parameter. Callers can pass any number of values, and the function decides what to do with them.
The same unpacking syntax works at the call site. Placing one star before a sequence passes its items as separate positional arguments, and two stars before a dictionary passes its entries as keyword arguments.
These features are common in wrapper functions that pass arguments on to another function, and in libraries that accept many optional settings.
Worked example
def total(*nums):
return sum(nums)
def describe(**info):
return info
print(total(2, 3, 5))
print(describe(name="Ana", age=30))
- Inside total, nums is the tuple (2, 3, 5).
- Its sum is .
- Inside describe, info is the dictionary {'name': 'Ana', 'age': 30}, which the function returns unchanged.
Check: passing the sequence [2, 3, 5] with the unpacking syntax also gives 10, because the same three numbers are passed.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? def total(*nums): return sum(nums) print(total(8, 2, 4))
Medium
What does this Python code print? def total_all(*args, **kwargs): return sum(args) + sum(kwargs.values()) print(total_all(2, mode=8, color=1))
Hard
What does this Python code print? def f(a, b=10, *args, c=1, **kw): return a + b + sum(args) + c * len(kw) print(f(4, *[1], flag=4))