Ever seen this in Python?
if (n := len("Hello")) > 3:
print(n)
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: ")
You can write:
while (name := input("Name: ")):
print(name)
🔥 Why use it?
- Cleaner loops
- Avoid repeated calculations
- Useful in
if,whileconditions - 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)