Introduced in Python 3.8, the Walrus Operator (:=
) is a feature that allows you to assign a value to a variable as part of an expression. It makes code more concise and reduce repetition, especially in loops and conditional statements.
What Does the Walrus Operator Do?
The Walrus Operator assigns a value to a variable and evaluates it in the same expression. This eliminates the need for separate lines for assignment and evaluation.
Syntax:
variable := expression
Common Use Cases
1. In While Loops
You can use the Walrus Operator to assign a value within the loop's condition, avoiding redundant calculations.
Example:
# Without Walrus Operator:
numbers = [1, 2, 3, 4, 5]
while len(numbers) > 0: # length checked every time
n = len(numbers) # assigned separately
print(numbers.pop())
# With Walrus Operator:
numbers = [1, 2, 3, 4, 5]
while (n := len(numbers)) > 0: # assign + check in one step
print(numbers.pop()) # Removes and prints the last element
The Walrus Operator avoids calling len(numbers)
twice.
2. In If Statements
The Walrus Operator can evaluate and assign a value within an if
condition.
Example:
# Without Walrus Operator:
names = ["Alice", "Bob", "Charlie"]
name = input("Enter a name: ")
if name in names:
print(f"Hello, {name}!")
else:
print("Name not found.")
# With Walrus Operator:
names = ["Alice", "Bob", "Charlie"]
if (name := input("Enter a name: ")) in names:
print(f"Hello, {name}!")
else:
print("Name not found.")
Here, you don’t need an extra line for name = input(...)
.
3. Streamlining Input Loops
A common pattern in Python is asking for user input repeatedly. The Walrus Operator simplifies this process by combining assignment and condition checking.
Example:
# Without Walrus Operator:
foods = []
food = input("What food do you like?: ")
while food != "quit":
foods.append(food)
food = input("What food do you like?: ")
print("Your favorite foods:", foods)
# With Walrus Operator:
foods = []
while (food := input("What food do you like?: ")) != "quit":
foods.append(food)
print("Your favorite foods:", foods)
Here,
(food := input(...))
assigns the user input tofood
.- The condition checks if
food
is not"quit"
, and if so, appends it to thefoods
list. - This is cleaner and avoids repeating
input(...)
.
4. Avoiding Redundant Computations
The Walrus Operator is useful when a value is both needed in a condition and later reused in the body of a loop or statement.
Example:
# Without Walrus Operator:
data = [10, 20, 30, 40, 50]
total = sum(data)
if total > 100:
print(f"The sum is {total}, which is greater than 100.")
# With Walrus Operator:
data = [10, 20, 30, 40, 50]
if (total := sum(data)) > 100:
print(f"The sum is {total}, which is greater than 100.")
Here,
- The sum of
data
is calculated once, assigned tototal
, and used in both the condition and the message. - The Walrus Operator combines assignment + condition neatly.
Benefits of the Walrus Operator
- Reduces Repetition: Combines assignment and evaluation into one step.
- Improves Performance: Avoids redundant calculations, especially in loops.
- Streamlines Code: Makes code shorter and more readable when used correctly.
Potential Drawbacks
- Readability Concerns: Overusing the Walrus Operator can make code harder to understand. Avoid using it in overly complex expressions.
- Limited to Python 3.8+: Code using the Walrus Operator will not run in older Python versions.
When to Use the Walrus Operator
- Use it when it simplifies code and avoids redundant calculations.
- Avoid using it in cases where it might obscure the intent of the code.
👉 Next tutorial: Python Function Caching