Unpacking
def foo(a, b):
print(a, b)
= [1, 2]
x *xs) # Unpacks the values in x into positional args.
foo(# As if you'd called
1, 2)
foo(
= {'a': 1, 'b': 2}
d **d) # Unpacks into param `d`, a dict.
foo(# As if you'd called
=1, b=2) foo(a
Writing def foo(*args) ...
creates a function that accepts zero or more positional args, slurping them all into a list:
def foo(*stuff):
print(stuff)
= [1, 2]
x *x) # Unpacks `x`, and prints out `[1, 2]`.
foo(# Works as if you'd called
1, 2) foo(
This effectively unpacks x, then re-packs it into the stuff
param in the body of the function.
Writing def foo(**named) ...
creates a function that accepts zero or more named args, and which then slurps them all into a dict:
def foo(**named):
print(named)
# foo(1, 2, 3) # ERROR
=1, b=2, c=3) # prints out a dict
foo(a
# And note:
= {'a': 11, 'b': 12, 'c': 13}
d **d)
foo(# Works as if you'd called
=11, b=12, c=13) foo(a
This effectively unpacks d
into keyword-args, then repacks it into a dict (the named
param) in the body of the function.
This is all separate from the other type of unpacking (“extended iterable unpacking”):
*b, c = [1, 2, 3, 4, 5] # `b` gets `[2, 3, 4]`. a,
There’s no **whatever
(“named args”-style) syntax for this kind of unpacking.