In this article you will learn about a cool feature which you might not even know exists in Python. i.e The Walrus(:=) operator. The operator gets its name from its resemblance to the eyes and tusks of a walrus (:=).

A Walrus

The Walrus operator was introduced in Python 3.8. It allows you to assign values to variables as a part of an expression. We can use it to create, assign and use variables in the same statement.

The operator is particularly useful when you want to compute a value and use it in the same line.

Syntax and basic usage

The syntax of the Walrus operator is as shown below:

(var := expression)
copy

Where var is the name of the variable and expression evaluates to the value to be assigned to the variable.

The parentheses are necessary, if you don't use them you will get a SyntaxError.

The syntax returns the result of the expression.

Consider the following example:

ExampleEdit & Run
result = (a := 8) * a

print(a)

print(result)
copy
Output:
8 64 [Finished in 0.01027001067996025s]

In the example shown above the (a := 8) does two things:

  • Creates a variable a and assigns it the value 8.
  • Returns the value of a, which is 8.

After this, the variable a is available in the current scope. The returned value (8) is then multiplied by the value of a (which is also 8), and the result (64) is assigned to the variable result.

The fact that we can use variable  a in the same statement it is created is what makes this feature powerful. It allows for more concise and expressive code by combining assignment and computation into a single step.  This eliminates the need for separate lines to define and use the variable, especially in loops, conditionals, and other contexts where intermediate values are needed immediately.

In the following sections, we will explore cases where the walrus operator proves to be particularly useful.

In Conditional logic

We can use the walrus operator in if statements to create intermediate variables. Consider the following examples:

ExampleEdit & Run

without walrus operator

value = int(input("Enter a number: "))

if value % 2 == 0:
    print(f"{value} is even.")
else:
    print(f"{value} is odd.")
copy
Output:
Enter a number: 9 9 is odd.

If we use the walrus operator, we can include the assignment of the value variable in the if statement as shown below.

ExampleEdit & Run

with walrus operator

if ( value := int(input("Enter a number: ")) )%2 == 0:
    print(f"{value} is even.")
else:
    print(f"{value} is odd.")
copy
Output:
Enter a number: 7 7 is odd.

Simplifying Loops with Input or Computations

Consider the following examples:

ExampleEdit & Run

without using walrus operator

while True:
    user_input = input("Enter a number (or 'quit' to exit): ")
    if user_input == "quit":
        break
    print(f"You entered: {user_input}")
copy
Output:
Enter a number (or 'quit' to exit): 12 You entered: 12 Enter a number (or 'quit' to exit): 24 You entered: 24 Enter a number (or 'quit' to exit): quit

In the above case, the program will indefinitely prompt user to enter something until the user enters 'quit' in which case the program will exit. Let us look at the same program using the walrus operator.

ExampleEdit & Run
while ( user_input := input("Enter something (or 'quit' to exit): ") ) != "quit":
    
    print(f"You entered: {user_input}")
copy
Output:
Enter a number (or 'quit' to exit): 12 You entered: 12 Enter a number (or 'quit' to exit): 24 You entered: 24 Enter a number (or 'quit' to exit): quit

As you can see above, the Walrus operator allows us to achieve the same functionality more concisely with less lines of code.

In List Comprehensions

List comprehension is a very convenient syntax that allows us to combine list building, conditional evaluation and loop logic, all into a single, concise expression.

We can supplement list comprehension with the walrus syntax to make it even more powerful and expressive.

Consider the following examples:

ExampleEdit & Run

without walrus operator

numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers if x**2 > 10]

print(squares) 
copy
Output:
[16, 25] [Finished in 0.009974717162549496s]

In the above example, the x ** 2 is computed twice, we can avoid such redundancy by using the walrus operator.

ExampleEdit & Run

with walrus operator

numbers = [1, 2, 3, 4, 5]

squares = [y for x in numbers if (y := x**2) > 10]

print(squares)  
copy
Output:
[16, 25] [Finished in 0.01004956103861332s]

As you can see above the walrus operator allows us to avoid repeating the expression x**2. Instead, we assign it to a variable y, then we re-use this variable.

Chained Walrus operators

Chaining walrus operators (using multiple := assignments in a single expression) is technically possible, but it can easily lead to unreadable or error-prone code.

I do not recommend use of chained walrus operators unless it is absolutely necessary, the following example is just for demonstration purposes. 

ExampleEdit & Run
if (a := (b := 10) * 2) < 100:
    print(a)
    print(b)
copy
Output:
20 10 [Finished in 0.009184898808598518s]

The innermost part of the condition, (b := 10), assigns the value 10 to the variable b,  returns the value 10 as part of the expression. Next, this result (10) is multiplied by 2, yielding 20, which is assigned to variable a, and returned. The if statement then checks whether a (which is 20) is less than 100.

Conclusion

Practically speaking, you can use the walrus operator in any valid python statement. However, in some scenarios, the syntax can make code harder to read or unnecessarily complicated. You should, therefore use this feature in cases where it  improves clarity, reduces redundancy, or simplifies conditional logic.