If you have studied the C/C++ language, you might be familiar with using the assignment operator ":=".
However, in Python, as you have noticed, we simply use the equal sign ("="). Starting with version 3.8
of the Python programming language, a new operator called the walrus operator (in Romanian, morsa) has been introduced:
considered one of the greatest improvements in this version because assignment expressions were introduced.
ESSENCE
The walrus operator allows for assigning values within an expression.
Example. Reading values from the keyboard. Suppose we want to read integer values until
we input 0, storing them in a simple list. We can now write it like this in Python:
Very important! Examples found on the Internet are often not deeply analyzed...
The walrus operator is very powerful, and the type of data held by the variable depends heavily on how
the code is written. In the example above, because we used parentheses within the boolean expression,
the type of the variable value is int, which is what we intended:
If we remove the parentheses from the assignment expression, the variable value will hold a
boolean value (True / False), which is not needed in this case and results in completely erroneous data.
Why does this happen? Since the assignment is performed at the level of the logical comparison between the assignment
expression and the value 0, it is considered of boolean type because 0 is interpreted
as False – pay attention to the operator precedence in Python!
Two parentheses... Python can be quite nuanced, isn't it? So, be very careful! We wrote 5 lines of
code and could already make a mistake.
Important! Keep in mind that the walrus operator can significantly simplify and optimize your code
in certain situations. However, it can also increase complexity and make the code harder to understand. Therefore,
it is recommended to use this operator with caution and avoid overusing it.
This operator has not been implemented for the online editor on the site, so you can only use it on your
computer where you have the Python programming environment (version 3.8+) installed.
As Seen On
Subscribe to our YouTube channel for more Python tutorials, tips, and resources.