3 ms·
I'm puzzled by this example: sums = [s for s in [0] for x in data for s in [s + x]] Why would you do "for s in" twice? Is that intentional? It would make
by andreasvc 6y ago
I'm puzzled by this example:
sums = [s for s in [0] for x in data for s in [s + x]]
Why would you do "for s in" twice? Is that intentional? It would make more sense to me if the variables would have been different. And why would you want to add 0 to numbers?! Curious about a real world use case for this.
- megaman821 6y agoIt is a nested loop. I don't find it very readable but the single line formatting makes it worse.
- duckerude 6y agoI 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.
- deleted 6y ago[deleted]
- nurettin 6y agos for s in [0] # for every s of 0 (there is only one) for x in data # for every x in data for s in [s + x] # s is s + x. so s = 0 + x[0], then s = (0 + x[0]) + x[1], then (0 + x[0] + x[1]) + x[2] it results in an array of rolling sums. Edit: someone already answered, I am blind.