Unpacking into a call (f(*a, **kw))
Put * before a list or tuple, or ** before a dict, and its items are passed to a function as separate arguments.
Used in 70 lessons of the course, from 01.02.
When you call a function, * before an iterable spreads its items out as positional arguments. ** before a dict spreads its pairs out as keyword arguments, using the keys as the names.
Think of it this way: f(*[1, 2]) is the same as f(1, 2). And f(**{"a": 1}) is the same as f(a=1).
Why write it this way? Because the data often already lives in a list or a dict, and you don't want to pull the items out one by one.
In the course you will see print(name, *describe_blocks(message), sep="\n "). Here describe_blocks returns a list of strings and * hands them to print as if you had typed them one by one. With sep they are split by a newline and an indent.
Don't confuse this with *args in a def: there * collects arguments; in a call it spreads them.
Reach for it when: you already have the arguments in a list, tuple or dict and want to pass them to a function as separate values.
Examples
Common mistake
def add(a, b):
return a + b
print(add(*[1, 2, 3]))Why: The `*` spreads three items, but the function only accepts two arguments.
How to write it: Pass only as many items as there are parameters, for example with a slice: add(*[1, 2, 3][:2]).
Common mistake
def show(a, b):
print(a, b)
show(*{"a": 1, "b": 2})Why: A single `*` on a dict spreads the keys, not the values.
How to write it: Use ** to pass the pairs by keyword: show(**{"a": 1, "b": 2}).
