The walrus operator (:=), added in Python 3.8, assigns a value to a variable and evaluates to that value at the same time, inside a single expression. It's most useful for avoiding a repeated computation: without it, you would often compute a value once to check it, then compute it again to use it.
#how it works
1
Plain assignment is a statement
Ordinary = does not produce a usable value of its own.
2
The walrus operator is an expression
:= assigns a value and also evaluates to that value in the same breath.
3
Common inside if and while conditions
The checked value becomes immediately available right after the condition.
4
Also useful in comprehensions
Avoids computing an expensive value twice inside a filtering expression.
5
Often needs parentheses
Many surrounding contexts require wrapping it in parentheses to keep the syntax unambiguous.
#example
data = [1, 2, 3, 4, 5, 6]
total = sum(data)
if total > 10:
print(f"Total is {total}")
if (total := sum(data)) > 10:
print(f"Total is {total}")
Output
Total is 21
Total is 21
1The first version computes sum(data), stores it in total, then checks it — two separate steps.
2The second version does both in the if line itself: total := sum(data) assigns and evaluates to 21 in one expression, which the > 10 comparison then uses immediately.
3Either way, total is available afterward for the f-string — the walrus operator simply collapses "compute, then check" into a single line.
#use cases
Avoiding calling an expensive function twice — once to check a condition, once to use the result
Reading a value inside a while loop condition and reusing that same value inside the loop body
Filtering inside a list comprehension while keeping the computed value for reuse
Making short validation checks more compact in scripts and one-off tools
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →