MyInternships.in

Python Advanced

Python Walrus Operator

The walrus operator (:=) lets you assign a value to a variable as part of a larger expression, saving you from writing a separate assignment line first.


What is the Walrus Operator?

Introduced in Python 3.8, the walrus operator := creates what is called an assignment expression: it assigns a value to a name and also produces that value as a result, all within a single expression, unlike a normal = assignment statement.

Basic walrus usage
Python
if (n := 10) > 5:
    print(f"{n} is greater than 5")

Using it in a while Loop

A common use case is reading input or data until some condition is met. Without the walrus operator, you often need to assign a value before the loop and again inside it. With :=, you can do both in one line.

Reading until empty input
Python
# Without walrus
line = input("Enter text: ")
while line != "":
    print("Got:", line)
    line = input("Enter text: ")

# With walrus
while (line := input("Enter text: ")) != "":
    print("Got:", line)

Using it in Comprehensions

The walrus operator also helps inside list comprehensions when you need to use the result of an expensive computation more than once, without repeating the computation.

Avoiding repeated calls
Python
data = [1, 4, 9, 16, 25, 36]

# Only keep square roots that are whole numbers, without calling sqrt twice
import math
results = [root for n in data if (root := math.sqrt(n)).is_integer()]
print(results)

Readability Considerations

The walrus operator is a convenience, not a requirement — it can make code shorter, but overusing it can also make expressions harder to read. Use it when it removes clear duplication, and skip it when a plain assignment statement is easier to follow.

💡

A good rule: reach for := when you would otherwise compute or fetch the same value twice — once to test it, once to use it.

⚠️

The walrus operator requires parentheses in most contexts, like (n := value), and cannot be used as a plain top-level statement in place of =.

Without walrusWith walrus
value = get()\nif value:if (value := get()):
x = compute()\nresults = [x for i in data][x for i in data if (x := compute())]

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships