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.
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:
It's subtly different in behavior (it will always reassign
n, which can make a difference ifnis a more complex expression or a weirdo@propertyor 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.
Try it online!
which outputs:
Note that mixing the conditional expression with a listcomp makes for very hard to read code, and
itertools.accumulatecould do this job with rather less hand-rolled ugliness, with something likerunning_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.