Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Ah, 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: