Practice: *args and **kwargs

« Read the chapter

Q1. Average of many numbers

BeginnerCoding

Write `average(*nums)` that returns the mean of the numbers. Print `average(2, 4, 6, 8)`.

Goal: Collect values with *args.

Q2. Print options sorted

BeginnerCoding

Write `show(**kwargs)` that prints each `key=value` pair in alphabetical key order. Call `show(b=2, a=1, c=3)`.

Goal: Read **kwargs.

Q3. Longest word

IntermediateCoding

Write `longest(*words)` that returns the longest word given (first one wins ties). Print `longest('pear', 'banana', 'kiwi')`.

Goal: Loop over *args.

Q4. Spread a list into a call

BeginnerCoding

Given `def volume(l, w, h)` and `dims = [2, 3, 4]`, call `volume` with the list unpacked and print the result.

Goal: Unpack a list with *.

Q5. Build a tag

AdvancedCoding

Write `tag(name, *content, **attrs)` that returns an HTML-like string. `tag('a', 'Home', href='/')` should give `<a href="/">Home</a>`. Print it.

Goal: Combine all parameter kinds.

Q6. Count of args

BeginnerOutput

What does this print?

Code
def f(*args):
    return len(args)

print(f(1, 2, 3), f())

Goal: Know args is a tuple.

Q7. Type of kwargs

BeginnerOutput

What does this print?

Code
def f(**kw):
    return type(kw).__name__

print(f(a=1))

Goal: Know kwargs is a dict.

Q8. Mixed call

IntermediateOutput

What does this print?

Code
def f(a, *b, **c):
    print(a, b, c)

f(1, 2, 3, x=4)

Goal: Trace parameter filling.

Q9. Star in the call

IntermediateOutput

What does this print?

Code
def f(a, b, c):
    return a + b + c

vals = (1, 2, 3)
print(f(*vals), f(*vals[:2], 10))

Goal: Unpack sequences in calls.

Q10. Keyword-only

IntermediateOutput

What does this print?

Code
def f(*items, sep='-'):
    return sep.join(items)

print(f('a', 'b', 'c'))
print(f('a', 'b', sep='+'))

Goal: Keyword-only parameters.

Q11. Dictionary unpack

AdvancedOutput

What does this print?

Code
def f(x, y=0, **extra):
    return x, y, extra

d = {'x': 1, 'z': 9}
print(f(**d))

Goal: Unpack dictionaries.

Q12. Fix the header order

BeginnerDebugging

This function raises a SyntaxError. Fix it.

Code
def f(**kwargs, *args):
    print(args, kwargs)

f(1, a=2)

Goal: Order parameters correctly.

Q13. Missing star in call

IntermediateDebugging

The function should add the three numbers in the list but raises TypeError. Fix it.

Code
def add(a, b, c):
    return a + b + c

nums = [1, 2, 3]
print(add(nums))

Goal: Spread sequences.

Q14. Changing args

IntermediateDebugging

This code raises TypeError. Fix it so it prints the values with the first one doubled.

Code
def f(*args):
    args[0] = args[0] * 2
    print(args)

f(5, 6)

Goal: Know args is immutable.

Q15. Why use **kwargs?

BeginnerConceptual

In two or three sentences, explain when `**kwargs` is better than normal parameters.

Goal: Decide when to use kwargs.

Q16. Two meanings of the star

IntermediateConceptual

Explain the difference between `*` in `def f(*a)` and in `f(*a)`.

Goal: Separate packing and unpacking.

Q17. Wrapper that counts

AdvancedApplication

Write a function `counted(func, *args, **kwargs)` that returns a tuple of the call result and the number of positional arguments. Print `counted(max, 4, 9, 2)`.

Goal: Forward arguments.

Q18. Settings with defaults

IntermediateApplication

Write `make_user(name, **extra)` that returns a dictionary with `name` and a `role` defaulting to `'guest'`, plus any extras. Print `make_user('Asha', age=20)`.

Goal: Use kwargs for settings.

Q19. Merge dictionaries

IntermediateApplication

Given `x = {'p': 1}` and `y = {'q': 2}`, build a single dictionary using `**` and print it.

Goal: Use ** to combine.