What is the most idiomatic way to achieve something like the following, in Haskell:
foldl (+) 0 [1,2,3,4,5]
--> 15
Or its equivalent in Ruby:
[1,2,3,4,5].inject(0) {|m,x| m + x}
#> 15
Obviously, Python provides the reduce
function, which is an implementation of fold, exactly as above, however, I was told that the 'pythonic' way of programming was to avoid lambda
terms and higher-order functions, preferring list-comprehensions where possible. Therefore, is there a preferred way of folding a list, or list-like structure in Python that isn't the reduce
function, or is reduce
the idiomatic way of achieving this?
sum
isn't good enough?sum
, you may want to provide some different types of examples.sum()
actually provides limited functionality with this.sum([[a], [b, c, d], [e, f]], [])
returns[a, b, c, d, e, f]
for example.+
on lists is a linear time operation in both time and memory, making the whole call quadratic. Usinglist(itertools.chain.from_iterable([a], [b,c,d],[e,f],[]])
is linear overall - and if you only need to iterate over it once, you can drop the call tolist
to make it constant in terms of memory.