DEV Community

Cover image for Python’s := Operator Is Tiny… But Surprisingly Powerful
June
June

Posted on

Python’s := Operator Is Tiny… But Surprisingly Powerful

Ever seen this in Python?

if (n := len("Hello")) > 3:
    print(n)
Enter fullscreen mode Exit fullscreen mode

That := is the Walrus Operator

It lets you assign a value AND use it in the same expression.

Instead of:

name = input("Name: ")
while name:
    print(name)
    name = input("Name: ")
Enter fullscreen mode Exit fullscreen mode

You can write:

while (name := input("Name: ")):
    print(name)
Enter fullscreen mode Exit fullscreen mode

🔥 Why use it?

  • Cleaner loops
  • Avoid repeated calculations
  • Useful in if,while conditions
  • Makes some code surprisingly compact

⚠️ But don't overuse it. Shorter code ≠ better code.

Have you used Python’s Walrus Operator before?

Top comments (0)