I was recently reading over PEP 572 on assignment expressions and stumbled upon an interesting use case:
# Compute partial sums in a list comprehension
total = 0
partial_sums = [total := total + v for v in values]
print("Total:", total)
I began exploring the snippet on my own and soon discovered that :+= wasn't valid Python syntax.
# Compute partial sums in a list comprehension
total = 0
partial_sums = [total :+= v for v in values]
print("Total:", total)
I suspect there may be some underlying reason in how := is implemented that wisely precludes :+=, but I'm not sure what it could be. If someone wiser in the ways of Python knows why :+= is unfeasible or impractical or otherwise unimplemented, please share your understanding.
My understanding is that a major part of comprehension efficiency is that the calculations for each element in the original iterable can be performed in parallel. If you're calculating a running total, that has to be performed in series.
We already have sum(values), so what does this add in this use case?
If you want something for more general use cases, functools has reduce.
The itertools module provides a lot of the mechanisms to achieve the same result without bloating the language:
partial_sums = list(accumulate(values))
total = partial_sums[-1]