Python Walrus Operator (:=) Explained with Examples

Published 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

    Geração de números aleatórios seguros usando secrets em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Generate Secure Random Numbers in Python with secrets

    Learn how Python's secrets module generates cryptographically secure random numbers, tokens, and passwords using randbelow, token_hex, token_urlsafe, and compare_digest.

    Ler mais

    Tempo de leitura: 4 minutos
    01/06/2026
    Pattern matching com match case em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python match-case: Pattern Matching Explained

    Learn how Python match-case works for structural pattern matching, including values, sequences, dictionaries, guards, and dataclasses with practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    30/05/2026
    Como resolver loop infinito que nunca termina em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Why Does My Loop Never End? Find the Solution

    Find out why your Python loop never ends and learn how to fix infinite loops caused by missing increments, wrong

    Ler mais

    Tempo de leitura: 6 minutos
    29/05/2026
    Logo do Python com as palavras global e local
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Variable Scope Explained Clearly

    Learn Python variable scope with clear examples of local, global, enclosing, built-in scope, LEGB rules, global, nonlocal, and common mistakes.

    Ler mais

    Tempo de leitura: 9 minutos
    28/05/2026
    Comparativo dos melhores cursos de Python para aprender programação
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    8 Best Python Courses for Beginners in 2026

    Compare the 8 best Python courses for beginners in 2026, including Academify, Alura, Udemy, Coursera, Codecademy, Harvard CS50, EBAC, and

    Ler mais

    Tempo de leitura: 7 minutos
    28/05/2026
    Como usar f-strings para formatar números e moedas em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python f-strings: Format Numbers and Currency

    Learn how to use Python f-strings to format numbers, currency, percentages, alignment, and zero-padding with clean and practical examples.

    Ler mais

    Tempo de leitura: 6 minutos
    28/05/2026