Python equivalent to clojure reductions

Viewed 98

In Clojure, we have a function like this

(reductions str ["foo" "bar" "quax"])
=> ["foo" "foobar" "foobarquax"]

or

(reductions + [1 2 3 4 5])
=> [1 3 6 10 15]

It's basically just reduce but it collects the intermediate results.

I'm having trouble finding an equivalent in Python. Does a base library function exist.

Python 3

2 Answers

You can use itertools.accumulate

from itertools import accumulate

l = [1, 2, 3, 4, 5]

print([*accumulate(l)])

Prints:

[1, 3, 6, 10, 15]

Since Python 3.8 we can use assignment expression :=:

data = ["one", "two", "three"]

item = ""
print([item := item + v for v in data])
Related