Python / Core Python Fundamentals Interview Questions
What is the walrus operator (:=) and when is it useful?
The walrus operator (:=), introduced in Python 3.8 (PEP 572), is the assignment expression operator. It assigns a value to a variable as part of a larger expression rather than as a standalone statement. The name comes from its resemblance to a walrus face with tusks.
# Without walrus â evaluate twice data = fetch_data() if data: process(data) # With walrus â evaluate once, assign, and test in one expression if data := fetch_data(): process(data) # Classic use: while loop reading chunks from a file with open('large.bin', 'rb') as f: while chunk := f.read(8192): process_chunk(chunk) # Filtering with a computed value â avoid calling the function twice results = [cleaned for raw in records if (cleaned := clean(raw)) is not None]
The walrus operator is most valuable when you need to compute a value, test it, and use it — and calling the computation twice would be wasteful or have side effects. Common patterns: while loops reading from streams, filtering list comprehensions where the filter function is expensive, and reducing nested if-statements.
Avoid overusing it — plain assignment on a separate line is often more readable. The walrus is idiomatic in tight loops and comprehensions; in most other code the conventional two-step (assign then test) is clearer.
More Related questions...