3 ms·
I wouldn't endorse that code, but it does make sense. You can read it like this: sums = [] s = 0 for x in data: s = s + x sums.append(s) `fo
by duckerude 6y ago
I wouldn't endorse that code, but it does make sense. You can read it like this:
sums = []
s = 0
for x in data:
s = s + x
sums.append(s)
`for s in [0]` assigns 0 to `s`, as an initial value. `for s in [s + x]` adds `x` to `s`. Both instances of `s` are the same variable, there's no shadowing going on.
- andreasvc 6y agoAh, I see. That really doesn't deserve to be called an idiom, it's a clever hack. But it's nice to know about it. It seems less ugly than the walrus operator to me, and it doesn't leak the variable outside of the comprehension.