Python's Walrus Operator (:=) was introduced in Python 3.8 as per PEP 572.
It allows for assignment expressions that enable you to assign values to variables as part of an expression. This feature can be quite handy but also a bit tricky for beginners to understand correctly.
One may think about :=
operator as an "in-place" assignment.
Look at this sample:
>>> a = (b := 5) * 4
20
>>> b
5
a
here is assigned an expression 5 * 4
, while the part of this expression, marked as b
. After evaluation we get b
equal to 5.
Quiz
Which code sample correctly demonstrates the use of Python's Walrus Operator (:=)
?
Sample 1
# Using Walrus Operator in a while loop
a = [1, 2, 3, 4, 5]
while (n := len(a)) > 0:
print(n)
a.pop()
Sample 2
a = [1, 2, 3, 4, 5]
if n := len(a) > 3:
print(f"List has {n} elements")
Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usual, the correct answer will be explained in a comment.
Top comments (0)