Can these sorts of if/else statements be boiled down with a walrus operator?

91 Views Asked by At

I have read up blogs and tutorials around the := operator but I am still trying to wrap my head around how to know when to use it. I understand its purpose is to improvement maintainability, avoiding potential code duplication, and assignments in comprehensions but I am wondering if it can be used to replaced something like:

n = 2
for m in [1,2,3,-9,5]:
    if m > n:
        n = m

Yes, I know I can sort the list. This question is less about algorithm discussions but more about how to identify when/where to use the := operator.

1

There are 1 best solutions below

1
On

You wouldn't bother with the walrus, since it doesn't aid you in any way in this sort of scenario. You could use a conditional expression though:

for m in [1,2,3,-9,5]:
    n = m if m > n else n

It's subtly different in behavior (it will always reassign n, which can make a difference if n is a more complex expression or a weirdo @property or the like), but it's otherwise equivalent.

The only use for a walrus would be to maintain a running maximum in a listcomp or the like, e.g.

n = 2
running_maximums = [n := m if m > n else n for m in [1,2,3,-9,5]]
print(running_maximums)
print(f'n={n}')

Try it online!

which outputs:

[2, 2, 3, 3, 5]
n=5

Note that mixing the conditional expression with a listcomp makes for very hard to read code, and itertools.accumulate could do this job with rather less hand-rolled ugliness, with something like running_maximums = list(accumulate([1,2,3,-9,5], max, initial=n)). Or if you only want new values in the output when they change, [n := m for m in [1,2,3,-9,5] if m > n]. This is all fairly contrived and unlikely to be useful in most cases, but it's the best I can give you on useful use of the walrus in this scenario.