What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Walrus Operator in Python: When to Use It? (with Examples)

  • Feb 15, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Komal Gupta
Walrus Operator in Python: When to Use It? (with Examples)

Greetings, Pythonolic, Are you eager to discover something new about python today? We have all used mathematical operators and functions that are familiar to us all, such as logical operators, identical operators, etc. Today, we will talk about a new Operator known as Walrus Operator and how does it work?

What is Walrus Operator in Python?

Walrus Operator in Python allows you to assign values to variables as part of an expression. It was first made available in Python 3..8 and later. In layman's terms, it combines Python's Assignment and Equality operators in a single line of code.

Here is the syntax:

variable := expression


It got its name from the operator symbol (:=) mimicking the eyes and tusks of a sideways walrus (colon equals operator).

The biggest advantage of the walrus operator is to make writing codes easier. In the past, you had to collect each user input into a distinct variable before passing it to the for loop to check its value or apply a condition. The walrus operator cannot be used as a stand-alone statement; this is a crucial distinction to make.

Example

First, we will print a list of numbers until its value is equal to 0, with a simple while loop.

num=int(input("Enter a number"))
while num > 0:
    print(num)
    num=num-1

 

Output:

10
9
8
7
6
5
4
3
2
1

 

We can perform the same task with the use of a walrus operator:

number = int(input("Enter a number: "))
while number > 0:
    print(number)
    (number := number - 1)

 

Output:

10
9
8
7
6
5
4
3
2
1

 

The value of the integer is reported and then updated using the walrus operator (:=) on each iteration of the loop. When a number is updated by the walrus operator (:=), it is decremented by 1. The number is updated and given a new value using the phrase (number:=number - 1). The expression is not required to be enclosed in parentheses, and doing so has no impact on the code.

The cycle repeats until the value of the number drops to or equals 0. The loop then ends, and the program is finished.

You might be wondering why we enclosed the walrus operator line of code in parenthesis. This is because python will give you a syntax error if you try to use the walrus operator as the assignment operator. It is designed in a way that prevents you from using it as an assignment operator, but you can if you add parentheses.

The visual similarity between the assignment operator (=) and the equality comparison operator (==) might potentially result in defects, which is one of the primary reasons assignments were never considered expressions in python from the start. To prevent problems with the walrus operator, much thought went into the introduction of assignment expressions.

The fact that the (:=) is a crucial component is that the walrus operator is never allowed as a direct replacement for the = operator, and vice versa.

number = int(input("Enter a number: "))
while number > 0:
    print(number)
    number := number - 1

 

Output:

  Cell In[10], line 4
    number := number - 1
           ^
SyntaxError: invalid syntax

 

When to use the Walrus Operator?

You have two options either going with the assignment operator or the walrus. But both are used in different scenarios. The assignment operator (=) just assigns a value to a variable for future use, whereas the walrus operator (:=) evaluates the walrus operator expression and assigns the result to the variable name. Also returning will be that value.

As we mentioned, it is great for simplifying the code in the following situations:

  1. Repeated function calls can make your code slower than necessary.
  2. Repeated statements can make your code hard to maintain.
  3. Repeated calls that exhaust iterators can make your code overly complex

It also simplifies the process of iterating over a list or a dictionary in python. Check the code below:

numbers = [1, 2, 3, 4, 5]
for i, n in enumerate(numbers):
    if (j := i + n) > 3:
        print(j)

 

Output: 

5
7
9

 

In this code, the walrus operator is used in the if statement to both assign the value of i + n to the variable j and test the condition j > 3 in the same line. If the condition is true, the code prints the value of j.

Situations where it can’t be used

The walrus operator is not supported inside lambda functions, as lambda functions are limited in scope and do not allow assignments. Check the example:

f = (lambda x: x := x + 1)

 

Output: 

  Cell In[21], line 1
    f = (lambda x: x := x + 1)
         ^
SyntaxError: cannot use assignment expressions with lambda

 

Another thing to note about the walrus operator has not supported inside list or dictionary comprehensions, as these are expressions that generate new lists or dictionaries, rather than statements that execute arbitrary code. Check the example:

list = [x := x**2 for x in range(5)]

 

Output: 

  Cell In[23], line 1
    list = [x := x**2 for x in range(5)]
            ^
SyntaxError: assignment expression cannot rebind comprehension iteration variable 'x'

 

Just remember before using this operator that it only works in python 3.8 or above versions. There are many times it’s possible for you to use the walrus operator, but where it won’t necessarily improve the readability or efficiency of your code. In those cases, you’re better off writing your code in a more traditional manner.

Conclusion

We learned about what is python's walrus operator and where it should and shouldn't be used. It is a valuable addition to the language that can make your code more concise. It is especially useful for tasks such as updating variables within loops and iterating over lists and dictionaries. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Komal Gupta
I am a driven and ambitious individual who is passionate about programming and technology. I have experience in Java, Python, and machine learning, and I am constantly seeking to improve and expand my knowledge in these areas. I am an AI/ML researcher. I enjoy sharing my technical knowledge as a content writer to help the community.