Back in Python 3.8, a new syntax quietly showed up and turned out to be surprisingly handy. It’s called the walrus operator (:=).
No, it’s not an actual walrus 🦭 — but it does help you write cleaner code with fewer lines.
🤔 What does it actually do?
In short: it lets you assign a value as part of an expression.
Think of it as saying:
“Hey Python, I want to save this value and use it right now — in one go.”
Let me show you:
while (line := input(">>> ")) != "exit":
print(f"You typed: {line}")
What’s going on here?
- You ask the user for input (
input(...)) - You store that in the variable
line
- Then immediately check if it’s
"exit"
All in one smooth line.
No need to write line = input(...) and then if line != "exit" on separate lines.
🧠 When should you use it?
Use it when:
- You want to assign and compare in the same line (e.g., in a
whileorif) - You’re inside a loop or list comprehension
- You want to avoid repeating the same function call
But a little tip: don’t overuse it. If it makes your code harder to read, maybe it’s not worth the cleverness.
🐍 Bonus example: reading a file line-by-line
while (line := file.readline()):
print(line.strip())
One-liner for looping through lines until the file ends. No line = file.readline() needed above the loop.
🔚 Final thoughts
At first, the walrus operator might look like some obscure Python trick. But once you start using it in the right places, it just clicks.
Try it a few times and you’ll find it creeping into your code naturally — just don’t go full walrus 🧠😄
SOCIAL SHARE CARD GENERATOR