Python assignment expressions

The := operator, introduced in Python 3.8, assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.

For example, given the following code:

buf = b""
while True:
    data = read(1024)
    if not data:
        break
    buf += data

This can be simplified as follows with the walrus operator:

buf = b""
while (data := read(1024)):
    buf += data

See also