*args & **kwargs
*args collects any number of positional arguments into a tuple. **kwargs collects keyword arguments into a dict:
def show(*args, **kwargs): print(args) # (1, 2) print(kwargs) # {'a': 3} show(1, 2, a=3)
Inside a function, loop over args like any tuple. For keyword arguments, kwargs.items() gives key/value pairs in the caller's keyword order; kwargs.values() gives just the values.
An expression such as sum(len(group) for group in groups) uses a generator expression: it supplies one calculated value at a time. Likewise, ", ".join(f"{k}={v}" for k, v in kwargs.items()) joins formatted strings with a comma and space; no items gives an empty string.
See it run
def pack(*args, **kwargs): count = len(args) return count, kwargs n, opts = pack(7, 8, 9, color="red") print(n, opts)
Watch what the pack() box collects from one call.
Practice *args & **kwargs
Exercise 1
total(*nums)returns the sum of all numbers given (total()is 0).describe(**info)returns"key=value"pairs joined by", ". For example,describe(name="Ada", lang="Py")gives"name=Ada, lang=Py".
Exercise 2
Define pack_count(*groups) to return the total number of items across any number of supplied lists; no groups gives 0. For example, pack_count([1, 2], [], [3]) is 3. It must stay fast with up to 20,000 groups.
Exercise 3
Define invoice(*amounts, **charges) to return the sum of all amounts plus all named charges, with no arguments returning 0. Define charge_names(**charges) to return the sorted charge names, including names whose charge is zero.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.