🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

Python Intermediate

What is Walrus Operator?

The := operator that assigns a value to a variable as part of an expression, introduced in Python 3.8.

The walrus operator (:=) combines assignment and expression evaluation. Instead of writing n = len(a); if n > 10, you can write if (n := len(a)) > 10. This is useful in while loops, list comprehensions, and conditional expressions.

Named after its resemblance to walrus eyes and tusks. It reduces code duplication when a value is needed both for a check and for subsequent use. Use sparingly to maintain readability.