Introduction
The walrus operator was introduced in Python 3.8 version, It was one of the new features added to Python. The name walrus was given, as the notation resembles the walrus eyes and tusks
Syntax
The syntax of walrus operator is :=
How it works?
The walrus operator is an assignment operator, it assigns values to the variables without inititalization
Example
Without Walrus Operator
name = "John Doe"
n = len(name)
if n != 0:
print(f'The length of name is {n}')
else:
print('The given name is empty')
With Walrus Operator
name = "John Doe"
if (n := len(name)) != 0:
print(f'The length of name is {n}')
else:
print('The given name is empty')
Instead of writing len(name)
everytime, it is assigned to a variable 'n' which can be used in anywhere in the program. The walrus operator reduces the effort of assigning the value to a variable and returning it
Know more about walrus operator and other new features added in Python 3.8 here
Thank you!
I hope this article was helpful for you, do share it with your friends.