DEV Community

Cover image for What Is the Walrus Operator (:=) in Python and Why It's So Useful
Eddie Goldman
Eddie Goldman

Posted on

What Is the Walrus Operator (:=) in Python and Why It's So Useful

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:

“I want to save this value and use it right now — in one go.”

Here’s an example:

while (line := input(">>> ")) != "exit":
    print(f"You typed: {line}")
Enter fullscreen mode Exit fullscreen mode

What’s happening 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 concise line.
No need to write line = input(...) and then if line != "exit" separately.


When should you use it?

Use it when:

  • You want to assign and compare in the same line (e.g., in a while or if)
  • You’re inside a loop or list comprehension
  • You want to avoid repeating the same function call

A word of caution: avoid overusing it. If it makes your code harder to read, it might not be worth the compactness.


Bonus example: reading a file line-by-line

with open("example.txt") as file:
    while (line := file.readline()):
        print(line.strip())
Enter fullscreen mode Exit fullscreen mode

This is a clean one-liner for looping through file lines without a separate assignment above the loop.


Final thoughts

The walrus operator might look unusual at first, but once you start using it in the right situations, it becomes a natural part of your coding toolkit.
Try it in small places, and you may find it simplifies your logic and keeps your code more expressive.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.