Python Walrus Operator (:=) Explained with Examples

Updated on: June 3, 2026
Reading time: 3 minutes
Uso do operador walrus para atribuições inline em Python

Python is known for its simplicity and readability, but that does not mean the language stops evolving. One of the most talked-about and initially controversial additions was the introduction of the walrus operator (:=). Officially called “Assignment Expressions,” this operator arrived with Python 3.8 and changed how we write certain control structures. If you are following a Python roadmap, understanding when and how to use this tool is a key step to leveling up your code.

The nickname walrus comes from the visual resemblance of := to the eyes and tusks of a walrus lying on its side. Its core purpose is to let you assign a value to a variable inside an expression — doing two things at once: defining a variable and returning its value so the rest of the line can use it immediately.

What is the walrus operator?

Normally the equals sign (=) stores a value. You cannot put that statement inside a condition like an if without a syntax error. The walrus operator breaks that limitation. It allows assignment to happen in the middle of a comparison or loop. According to PEP 572, the goal was to eliminate redundant calculations and repetitive “boilerplate” patterns.

Use in if statements

numbers = [1, 2, 3, 4, 5]

# Old style — two lines
size = len(numbers)
if size > 3:
    print(f"Large list with {size} elements.")

# With walrus operator — one line
if (n := len(numbers)) > 3:
    print(f"Large list with {n} elements.")

Use in while loops

A classic use case is reading user input until they type a specific word to exit:

# Old style — input() called twice
command = input("Type something: ")
while command != "stop":
    print(f"You typed: {command}")
    command = input("Type something: ")

# With walrus operator — input() called once
while (command := input("Type something: ")) != "stop":
    print(f"You typed: {command}")

Use in list comprehensions

When you need to apply a function to an item and use the result for both the filter and the output, the walrus avoids calling that function twice:

# Inefficient: f(x) called twice per item
results = [f(x) for x in data if f(x) > 0]

# Efficient with walrus: f(x) called once
results = [res for x in data if (res := f(x)) > 0]

Practical example: nested dictionary lookup

user_data = {"id": 1, "config": {"theme": "dark"}}

if (config := user_data.get("config")) and (theme := config.get("theme")):
    print(f"Selected theme: {theme}")

Here two values are captured in a chain. If “config” does not exist, the expression stops at the first part. A clean way to handle nested data without multiple indented if blocks.

= vs := at a glance

The regular = is a standalone statement that returns no value and can only appear at the start of a line or block. The walrus := is an expression that returns the assigned value and can appear inside if, while, list comprehensions, and other expressions. It requires Python 3.8 or later.

When NOT to use the walrus operator

The golden rule from the Zen of Python is that readability counts. If a line with := becomes so complex that a developer needs to pause to understand it, break it into two lines. Use it only where logic gains fluidity — not as a way to remove every equals sign from your code. Parentheses around the assignment expression are almost always required to avoid ambiguity.

Frequently Asked Questions

Does the walrus operator work on older Python versions?

No, it is only compatible with Python 3.8 or later. Running it on 3.7 or 2.7 raises a SyntaxError.

Can I use := to replace all my assignments?

Not recommended. Use it only when assignment happens inside an expression (like an if or while). For regular assignments at the start of blocks, keep using the plain =.

Does the walrus operator slow down code?

On the contrary — in many cases it improves performance by preventing a function or method from being called twice unnecessarily.

Why do I need parentheses around the walrus expression?

Parentheses help Python understand the order of operations, ensuring the assignment happens before the comparison.

Is it considered bad practice?

Not anymore. After the initial debates, it became a standard language tool. The bad practice is overuse that hurts code clarity.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Programador pensando enquanto analisa código em dois monitores
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Learn Programming from Scratch: Beginner Guide

    Learn programming from scratch with a practical roadmap covering logic, languages, tools, exercises, projects, debugging, Git, and consistent study habits.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    ícone de loop com o texto 'For' abaixo
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python for Loops: Complete Beginner Guide

    Learn Python for loops with sequences, range, enumerate, zip, dictionaries, nested loops, break, continue, comprehensions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Manipulação e formatação de strings em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Strings: Complete Beginner Guide

    Learn Python strings with creation, indexing, slicing, methods, formatting, Unicode, searching, validation, splitting, joining, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    código Python de uma tupla com o texto separado formando a frase "O que são tuplas?"
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Tuples: Complete Beginner Guide

    Learn Python tuples with creation, packing, unpacking, indexing, immutability, methods, named records, function returns, and practical examples.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    símbolo de PI
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Floats: Complete Beginner Guide

    Learn Python floats with decimal values, arithmetic, conversion, rounding, precision limits, comparisons, Decimal, math functions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    notebook mostrando tela a teclado
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Input and Output: Complete Guide

    Learn Python input and output with input(), print(), conversions, validation, formatting, files, command-line arguments, and practical interactive programs.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026