Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.9 — The Walrus Operator :=
Python · Example 2 of 2 Python 3.8+

Comprehension reuse and the lasting name

Check the line "price is now None": the name from the last test is still there. Then try y = (z := 5) + 1 with other numbers.

The walrus operator := assigns a value to a name inside an expression, so you can test a value and keep it in one step. It shortens loops that read until a stop signal and filters that need a computed value twice, and it is not worth using when it makes a line harder to read.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

With inbox = ["a", "b", "end", "c"], use a walrus loop with pop(0) to print each message until "end". Print a then b.

02

Use if (n := len("hello world")) > 5: to print Long text: 11.

03

Using a comprehension with a walrus, collect the squares greater than 20 from [2, 5, 3, 6] and print [25, 36].

Explain it without notes

01

What does the walrus operator do, and how is it different from =?

02

Show a loop that reads until a stop value, with and without :=.

03

Why does a name set with := inside an if still exist after the if?

04

When should you avoid the walrus operator?

Comprehension reuse and the lasting name Python 3.8+
Sign in to run this example in your browser.

Expected output

[64, 81, 16]
apple costs 30
no kiwi
price is now None
6 5