Member-only story
When and Why to Use :=
Over =
in Python
Very recently, Python 3.8 introduced the use of ‘colon equals’ (:=
), which is similar to the equals operator (=
). The use of this operator allows for speedup and shortened code, and it’s definitely valuable to understand.
This notation comes from a complaint rooted in mathematics. When we write equations in mathematics, we may write something like a=5
, a+b=7
. Then, one could use simple algebraic manipulation to find that b=2
. In this context, the equals sign means equality. The variables a
and b
are constant numbers, and while their value is not known at the initialization of the problem, it exists and does not change.
On the other hand, in mathematics, there exists a different notation for the relationship ‘x is defined to be y’. If one were to write x := y, it is not that x and y share a relationship of quantitative equality but that x is defined to be whatever value y is. It’s more one-way than symmetrical. This is a bit tricky to wrap your head around, but the notation is really only for long lists of variable definitions at the beginning of highly technical research papers.
Regardless, in the most recent version of Python 3.8 has emerged the accepted use of :=
, or the ‘walrus operator’ (it indeed does look like a horizontal walrus). While it doesn’t address the…