What is the walrus operator (:=) in Python?
Why Interviewers Ask This
Mid-level Python roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
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.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is the mutable default argument pitfall in Python?
Next
What is Python's structural pattern matching (match/case)?