Python Quiz: ๐Ÿ˜ฎ Walrus operator in Python.

vladignatyev

Vladimir Ignatev

Posted on December 8, 2023

Python Quiz: ๐Ÿ˜ฎ Walrus operator in Python.

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Sample 2

a = [1, 2, 3, 4, 5]
if n := len(a) > 3:
    print(f"List has {n} elements")
Enter fullscreen mode Exit fullscreen mode

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
vladignatyev
Vladimir Ignatev

Posted on December 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About