Udit Vashisht
Author: Udit Vashisht


New Walrus Operator in Python 3.8

  • 4 minutes read
  • 49 Views
New Walrus Operator in Python 3.8

What is new walrus operator in Python 3.8?

The official version of Python 3.8 was released in October, 2019.

What’s new in Python 3.8?

Before going in details about new Walrus Operator in Python 3.8, I will like to summarize what is new in Python 3.8 :-

New Feature PEP
Assignment Expression (Walrus Operator) PEP 572
Positional-only parameters PEP 570
f-strings support = for self-documenting expressions and debugging -
importlib.metadata (New module) -
Typing PEP 586

The Walrus Operator

The new assignment operator having notation := is the biggest and the coolest change in Python 3.8. It is called the Walrus operator due to its resemblance to the eyes and tusks of a walrus.

The walrus operator allows to assign and return a value in a single expression. For example, normally you will do this

# walrus_operator.py

a_value = "Hello"
print(a_value)

# Output
Hello

However, using the walrus operator, you can do it in a single expression as under:-

# walrus_operator.py

print (a_value := "Hello")

# Output
Hello

Basically, walrus operator helps us to do certain tasks with more convenience and does not bring anything new in terms of functionality.

In the following example, using the walrus operator helps avoid using len() twice:-

# walrus_operator.py

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

if (n:=len(a_list))>3:
    print(f'List is too long ({n} elements, expected <= 3)')

# Output
List is too long (5 elements, expected <= 3)

# In Python 3.7

a_list = [1, 2 , 3, 4, 5]
if len(a_list)>3:
    print(f'List is too long ({len(a_list)} elements, expected <= 3)')

# Output
List is too long (5 elements, expected <= 3)

So, in the above example using the walrus operator made our expression more convenient.

The walrus operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop.

# walrus_operator.py

inputs = list()
while (current := input("Write something: ")) != "quit":
    inputs.append(current)

However, the official documentation cautions to limit the use of the walrus operator to clean cases that reduce complexity and improve readability.



Related Posts

No related posts yet!

Search