DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on โ€ข Edited on

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.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how theyโ€™re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs