🐍 Python Intermediate

What is the walrus operator (:=) in Python?

Answer

The walrus operator (:=), introduced in Python 3.8, is an assignment expression that assigns a value to a variable as part of an expression. It allows assigning and using a value in the same expression. Example in a while loop: while chunk := file.read(8192): process(chunk). In a comprehension: results = [y for x in data if (y := process(x)) > 0] — computes y once and uses it in both the condition and output. In an if statement: if m := re.match(pattern, text): print(m.group()). The walrus operator reduces redundant computation and simplifies certain patterns. Use it sparingly — only when it genuinely improves readability. Never use it just to reduce line count; clarity is more important than brevity in Python.