A gotcha with the Walrus operator

InĀ New python syntax I was previously unaware of, I discussed some new operators I’d recently discovered. One of them is called the Walrus operator, which lets you write code like this:

list = ['a', 'b', 'c']
def get_one():
    if not list:
        return None
    return list.pop()

while one := get_one():
   print(one)

See where we do the assignment inside the while? That code returns:

c
b
a

Which is as expected. However, the Walrus operator is strict about needing a None returned to end the iteration. I had code which was more like this:

list = [('a', 1), ('b', 2), ('c', 3)]
def get_one():
    if not list:
        return None, None
    return list.pop()

while one := get_one():
    print(one)

And the while loop never terminates. It just prints (None, None) over and over. So there you go.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.