Flat_Eric Contemplating Data Type Conversions

Walrus Operator

I am the Walrus.

The Walrus Operator

Python is a living language. With every new release the Python development team adds new features, improves existing ones and occasionally removes things that are no longer needed. Keeping up with these changes is part of being a developer and the best place to do that is the official Python documentation:

Python 3.14 Official Documentation

The walrus operator := was introduced in Python 3.8 and is one of the more useful recent additions to the language. It is called the walrus operator because := looks like the eyes and tusks of a walrus on its side.

What Does the Walrus Operator Do?

The walrus operator is also known as the assignment expression. It allows you to assign a value to a variable and use that variable in the same expression at the same time. This is something the regular = assignment operator cannot do.

Without the walrus operator you often find yourself writing two separate lines, one to assign a value and one to use it. The walrus operator lets you combine them into one.

A simple example without the walrus operator:

The same example using the walrus operator:

Both produce the same result but the walrus operator version is more concise. The value is assigned to n and immediately used in the condition in a single expression.

Walrus Operator with a while Loop

One of the most common and practical uses of the walrus operator is inside a while loop. Instead of assigning a value before the loop and updating it inside, you can do both in the loop condition itself.

The walrus operator assigns the user input to user_input and immediately evaluates whether it equals "quit" in the same line. Clean, concise and easy to read.

Walrus Operator with a List Comprehension

The walrus operator is also useful inside list comprehensions when you need to perform a calculation and use the result in both the condition and the output without calculating it twice.

Without the walrus operator you would either need to calculate the value twice or use a regular loop instead. The walrus operator keeps it in one clean expression.

Walrus Operator with a Function

You can also use the walrus operator to assign and check the result of a function call in a single line. This avoids calling the function twice just to store and then check the result.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: match / case (Python 3.10)

Exercise 2: Exception Groups (Python 3.11)

Exercise 3: Improved f-strings (Python 3.12)

Exercise 4: Type Parameter Syntax (Python 3.12)

Exercise 5: Your Choice

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course