Assignment expressions
Before we look at some more complicated examples, we would like to briefly introduce you to a feature that was added to the language in Python 3.8, via PEP 572 (https://peps.python.org/pep-0572). Assignment expressions allow us to bind a value to a name in places where normal assignment statements are not allowed. Instead of the normal assignment operator =
, assignment expressions use :=
(known as the walrus operator because it resembles the eyes and tusks of a walrus).
Statements and expressions
To understand the difference between normal assignments and assignment expressions, we need to understand the difference between statements and expressions. According to the Python documentation (https://docs.python.org/3.12/glossary.html#term-statement), a statement is:
…part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, such as
if
,while
orfor
.
An expression...