Python := Walrus Operator in Python 3.8 (original) (raw)

Last Updated : 25 Oct, 2025

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())

`

**Explanation:

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:

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: