Assignment expressions (:=)

OptionalOptional

Juan Camilo ZúñigaBackend & data developer

The assignment expression := (nicknamed the walrus operator) assigns a value and returns it, so you can name a value in the middle of an expression. It exists since Python 3.8.

# Without it: call twice, or add a line before the if
if (n := len(items)) > 10:
    print(f"Too many items: {n}")

It shines in loops that read until there is nothing left:

while (line := file.readline()):
    process(line)

and in comprehensions that would otherwise compute something twice:

results = [y for x in data if (y := expensive(x)) is not None]

When not to use it

It is optional for a reason: a plain assignment on its own line is usually clearer. Reach for := when it removes a repeated call or an awkward extra line, not to make code shorter for its own sake.