Explain Codes LogoExplain Codes Logo

What does colon equal (:=) in Python mean?

python
assignment-expressions
walrus-operator
python-3.8
Alex KataevbyAlex Kataev·Mar 10, 2025
TLDR

Introducing the := operator in Python, fondly named the walrus operator. This operator is Python's way of saying "Why not assign and evaluate in one step?"

if (count := len(items)) > 5: print(f"Count is {count} — Whoa, slow down there!")

In this example, count runs len(items) and holds onto the result, ready for immediate use — no extra line or code rerun necessary. Efficiency just got a new best friend.

Unpacking the walrus

Before we understand why we need :=, let's put on our coding hats and explore what Python 3.8 unleashed with this walrus lookalike.

Assignment expressions, as these are formally termed, knit assignment and evaluation into one stitch, giving life to pylonic tales that := is Python's new hero.

How to unleash the walrus

  1. If-based decisions
# Old-school style: match = pattern.search(data) if match: do_something_amazing(match) # With the walrus: if (match := pattern.search(data)): do_something_amazing(match) # Walrus says, "One liner? No problem!"
  1. While loops
# Good old days: value = fetch_next() while value: process(value) value = fetch_next() # With the walrus: while (value := fetch_next()): process(value) # The walrus shrinks codes one loop at a time.
  1. List comprehensions
# Classic approach: processed = [process(x) for x in data if process(x) > threshold] # With the walrus: processed = [res for x in data if (res := process(x)) > threshold] # Walrus says, "arrow keys are so last year!"

Efficiency: The coding mantra

Redundancy is the bane of efficiency — Walrus guards against this by reducing separate lines for assignments and lowering the need for expensive operations (who needs gold-plated function calls anyway, right?).

Read through your code and the flow feels natural, kind of like scrolling through your favourite social media feed — all thanks to the walrus!

Don't trip over!

While the walrus operator is cool and fun, remember readability matters. Use it proudly but wisely — a cloaked code does no good. Stick to the principle of least astonishment and leave comments if you think the walrus may confuse other developers.

Transcending pseudocode

When converting pseudocode to Python, keep an eye for = and ==. In Python, == is used for equality comparisons, while in pseudocode = could be used for assignments. The walrus operator can help make the transition smoother.

Tips to tame the walrus

  1. Avert redundancy: Use := to skip recalculating values or refetching data — #savethememory!
  2. Radiate clarity: The walrus can declutter your code by making logic more immediate — #cleaniscool!
  3. Selective integration: Just like any tool, use the walrus operator where it fits — #beawalruswizard!