The walrus operator assigns and returns a value in an expression, reducing repetition
The walrus operator := is an assignment expression introduced in Python 3.8 (PEP 572). It assigns a value to a name and returns that value, so you can use it inside expressions where a plain assignment statement is not allowed, such as in while conditions, if conditions, and comprehensions. The main benefit is avoiding duplicated computation or a temporary variable that exists only to be tested. For example, while (chunk := file.read(8192)): processes chunks without reading twice. It can also be used in list comprehensions to avoid calling a function twice. The trade-off is readability: overuse can make expressions dense and hard to follow. The rule of thumb is to use it when it removes a real duplication and the expression remains clear, and avoid it when it saves only a line or two. Parentheses are usually required around the assignment expression to disambiguate it.
while (line := f.readline()): processes lines until an empty string is returned.
if (match := pattern.search(text)): avoids calling search twice.
[y for x in data if (y := transform(x)) is not None]: avoids recomputing transform.
It cannot be used as a standalone statement; it must be part of an expression.
Trade-off: reduces duplication but can hurt readability if nested or combined with complex expressions.
Common mistake: using := where a simple assignment would be clearer, making the code harder to read.
Common mistake: forgetting parentheses in conditions, which causes a SyntaxError.
Version note: introduced in Python 3.8. It is not available in 3.7 or earlier.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience