Python Principles
Python Q&A

What is the walrus operator in Python?

Answer:

The walrus operator := is a new feature in Python 3.8. It is similar to the assignment operator =, but it is an expression, not a statement.

This means you can use := in places where only an expression can go. For example, the following code is valid:

while (line := file.readline()) != "done":
    print(line)

In the code above, line will hold the value from file.readline() in each iteration of the loop.

If the code had used = instead, it would have resulted in a syntax error, since a = b is a statement, not an expression, so it is not comparable.