Question:
I have seen Python code, which makes use of the symbol :=
.
For example:
if (variable := random.randint(1,10)) > 5:
#Bloque de código...
It is not clear to me what is the usefulness of this symbol in Python.
- What does this symbol mean?
- What does this symbol do or what is it for in Python?
Answer:
What does this symbol mean?
This is the walrus operator , which was introduced with Python version 3.8.x (see What's New In Python 3.8 ).
This operator was proposed in PEP 572 :
From the abstract summary: This is a proposal for creating a way to assign to variables within an expression using the notation NAME: = expr.
From the reason for the proposal: Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.
What does this symbol do or what is it for in Python?
It fulfills the same function with which it was proposed in the first place: assign a value to a variable and have it evaluated as an expression.
Previously, if you wanted to evaluate an expression and use that result as a variable, you had to define a variable and then evaluate it.
import random
variable = random.randint(1,10)
if variable > 5:
print(f"El número {variable} es mayor a 5")
else:
print(f"El número {variable} es menor a 5")
If it is about doing an assignment in the conditional to evaluate the condition and have a variable that stores the result of the expression:
if (variable = random.randint(1,10)) > 5:
print(f"El número {variable} es mayor a 5")
else:
print(f"El número {variable} es menor a 5")
You get a syntax error:
if (variable = random.randint(1,10)) > 5:
^
SyntaxError: invalid syntax
Therefore before version 3.8.x, it was impossible to evaluate and assign in the same expression. Since Python offers the option of assigning expressions with the walrus operator, it is possible:
if (variable := random.randint(1,10)) > 5:
print(f"El resultado de la {variable} es mayor a 5")
else:
print(f"El número {variable} es menor a 5")
Broadly speaking, with this operator you can assign a value to a variable and evaluate its expression at the same time. This can be useful in certain situations, where you are concerned with reusing the result of a function, and thus not calling it more than once. See example in What's New In Python 3.8 article
if (cantidad_elementos := len(lista)) > 10:
print(f"Lista demasiado larga ({cantidad_elementos} elementos, se esperaban <= 10)")
This avoids calling len()
when formatting the message to be displayed, the defined variable cantidad_elementos
is called directly.