First Half Review

Good morning,

As I complete my review of the first half of the book, I came across some syntax that is not clear. From Ex. 24,

formula = secret_formula(start_point)
# this is an easy way to apply a list to a format string.
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))

What is the significance of the * that precedes formula? If I “break” the code by removing the asterisk (*), I receive an error. I understand that the * needs to be there, but I don’t understand why. What is the interpreter doing “sees” the *? My guess: The interpreter is referring back to the variable contents of ‘formula’. I hope these questions make sense.

Thank you very much!

Yes, the asterisk “unpacks” the elements of a sequence.
You can also do the reverse with function parameters.

def print_all(*args):
    # args is a tuple containing all arguments
    for arg in args: print(arg)

print_all(1,2,3)

def print_three(a,b,c):
    print(a)
    print(b)
    print(c)

three = (1,2,3)
print_three(*three) # unpack the tuple into the parameter list

And you can use two asterisks for named parameters:

def print_named(**kwargs):
    # kwargs is a dict of the named arguments
   for key, value in kwargs.items(): print(key, value)

print_named(fruit="apple" , vegetable="tomato")
3 Likes

Good evening,

@florian. Many thanks for the detailed explanation. Some of this is a little over my head at this point, but I believe I get the gist from your examples.

Yes, don’t worry. Just remember that the asterisk spreads out sequences. It’s super handy at times.

And you should only use variadic function parameters when you know that you really need them and why – and when you’re at that point, this will be no difficulty for you anymore.


Just for the sake of completeness, because I forgot this case: You can also unpack dictionaries.

# print_named like above
meal = {
    "fruit": "apple",
    "vegetable": "tomato"
}
print_named(**meal)
1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.