In this lesson, you’ll learn about the biggest change in Python 3.8: the introduction of assignment expressions. Assignment expression are written with a new notation
(:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.
Assignment expressions allow you to assign and return a value in the same expression. For example, if you want to assign to a variable and print its value, then you typically do something like this:
>>> walrus = False >>> print(walrus) False
In Python 3.8, you’re allowed to combine these two statements into one, using the walrus operator:
>>> print(walrus := True) True >>> type(walrus) <class 'bool'>
The assignment expression allows you to assign
walrus, and immediately print the value. But keep in mind that the walrus operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient, and can sometimes communicate the intent of your code more clearly.
One pattern that shows some of the strengths of the walrus operator is
while loops where you need to initialize and update a variable. For example, the following code asks the user for input until they type
# write_something.py inputs = list() current = input("Write something: ") while current != "quit": inputs.append(current) current = input("Write something: ")
This code is less than ideal. You’re repeating the
input() statement, and somehow you need to add
current to the list before asking the user for it. A better solution is to set up an infinite
while loop, and use
break to stop the loop:
# write_something.py inputs = list() while True: current = input("Write something: ") if current == "quit": break inputs.append(current)
This code is equivalent to the code above, but avoids the repetition and somehow keeps the lines in a more logical order. If you use an assignment expression, then you can simplify this loop further:
# write_something.py inputs = list() while (current := input("Write something: ")) != "quit": inputs.append(current)
This moves the test back to the
while line, where it should be. However, there are now several things happening at that line, so it takes a bit more effort to read it properly. Use your best judgement about when the walrus operator helps make your code more readable.
PEP 572 describes all the details of assignment expressions, including some of the rationale for introducing them into the language, as well as several examples of how the walrus operator can be used. The Python 3.8 documentation also includes some good examples of assignment expressions.
Here are a few resources for more info on using bpython, the REPL (Read–Eval–Print Loop) tool used in most of these videos: