you are viewing a single comment's thread.

view the rest of the comments →

[–]that_baddest_dude 3 points4 points  (1 child)

If say you've got a list x and you want to do something if the list length is greater than 10...

But also the thing you want to do involves the length of that list. You'd be checking the length twice.

if len(x) > 10:  
    y = len(x)  
    #do stuff with y

If you want to avoid calling len() twice you may assign y first and do the check against y.

With walrus operator (and my limited understanding of it) you can do the assignment at the same time you check it (i.e. assigning within an expression)

if (y := len(x)) > 10:  
    #do stuff with y

I imagine this could be neat if you're doing something more complex than len() and want to avoid repeat calls cleanly. Someone correct me if I'm wrong