Command Palette

Search for a command to run...

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

Walrus in a while loop and an if

Move "stop" to the front of the list and run it: the loop body never runs. Change the 10 to 25 and watch the if branch switch off.

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?

Walrus in a while loop and an if Python 3.8+
Sign in to run this example in your browser.

Expected output

got hello
got world
left in inbox: ['ignored']
20 characters is too long