3 ms·
You forgot the walrus operator! accum = initial series = [accum := bifun(accum, value) for value in seq] # result = series[-1] To be honest, this is the
by versteegen 3y ago
You forgot the walrus operator!
accum = initial
series = [accum := bifun(accum, value) for value in seq]
# result = series[-1]
To be honest, this is the first time I've used the walrus operator.
- wenc 3y agoThis is very nice. Replaces reduce() for me. Now to upgrade to Python 3.8! (stock Python on my cloud machine is still 3.7)
- kstrauser 3y agoAll hail the walrus! (Seriously, I like that.)
- daureg 3y agodoesn't it use a lot of memory since we're only interested in the last value?
- FreakLegion 3y agoYou can do the same thing with a generator. x = 0 deque((x := x + 1 for _ in range(10)), maxlen=0) print(x) >> 10 Using deque to consume generators is an old trick documented in the itertools recipes: https://docs.python.org/3/library/itertools.html#itertools-recipes https://docs.python.org/3/library/itertools.html#itertools-r...