Steven's Homepage

Walrus Operator

Assignment Expressions

By way of improving some code I wrote yesterday where I use casefold() twice on the same string within an expression. If the string was long then it might become expensive to compute the casefold over and over again, therefore, it would be of benefit if I could reuse the value.

With the walrus operator (Assignment Expressions[1]) I can assign the value of the casefold to a variable and reuse it within the expression.

The old code:

def word_count(words):
    vowels = {'a', 'e', 'i', 'o', 'u'}
    return sum(1 for w in words
               if w[0].casefold() in vowels or w[-1].casefold() in vowels)

becomes this with the walrus operator:

def word_count(words):
    vowels = {'a', 'e', 'i', 'o', 'u'}
    return sum(1 for w in words
               if (c := w.casefold())[0] in vowels or c[-1] in vowels)

References

  1. PEP 572 – Assignment Expressions