Open In App

Python := Walrus Operator in Python 3.8

Last Updated : 25 Oct, 2025
Comments
Improve
Suggest changes
12 Likes
Like
Report

The Walrus Operator (:=), introduced in Python 3.8, allows you to assign a value to a variable as part of an expression. It helps avoid redundant code when a value needs to be both used and tested in the same expression — especially in loops or conditional statements.

Syntax

variable := expression

The expression on the right-hand side is evaluated, assigned to the variable, and then returned.

Example 1: Using Walrus Operator in a while Loop

In this example, we use the Walrus Operator to assign the list length to a variable within the while loop condition.

Python
num = [1, 2, 3, 4, 5]

while (n := len(num)) > 0:
    print(num.pop())

Output
5
4
3
2
1

Explanation:

  • len(numbers) is assigned to n inside the loop condition.
  • The loop continues while n > 0, printing and removing elements until the list is empty.
  • This avoids calling len(numbers) repeatedly in separate statements.

Example 2: Comparing with and without Walrus Operator

Here, we compare two approaches - one using the Walrus Operator and the other without it, to extract names from a list of dictionaries.

Python
d = [
    {"userId": 1, "name": "rahul", "completed": False},
    {"userId": 1, "name": "rohit", "completed": False},
    {"userId": 1, "name": "ram", "completed": False},
    {"userId": 1, "name": "ravan", "completed": True}
]

print("With Python 3.8 Walrus Operator:")
for entry in d:
    if name := entry.get("name"):
        print(name)

print("Without Walrus operator:")
for entry in d:
    name = entry.get("name")
    if name:
        print(name)

Output
With Python 3.8 Walrus Operator:
rahul
rohit
ram
ravan
Without Walrus operator:
rahul
rohit
ram
ravan

Explanation:

  • In the first loop, name is assigned and checked in the same line using :=.
  • Second loop performs the same logic but requires two lines- assignment and condition separately.

Example 3: Simplifying User Input Loops

This example shows how the Walrus Operator can simplify continuous input loops by combining input reading and condition checking.

Without Walrus Operator

Python
foods = []
while True:
    f = input("What food do you like?: ")
    if f == "quit":
        break
    foods.append(f)

Output

What food do you like?: apple
What food do you like?: banana
What food do you like?: quit

With Walrus Operator

Python
foods = []
while (f := input("What food do you like? (type 'quit' to stop): ")) != "quit":
    foods.append(f)

Output

What food do you like?: apple
What food do you like?: banana
What food do you like?: quit

Explanation:

  • Input is directly assigned to food inside the while condition.
  • Loop continues until the user types 'quit', resulting in cleaner and more readable code.

Article Tags :

Explore