Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • 3
    sum isn't good enough? Commented Apr 28, 2012 at 18:32
  • 3
    not sure if this is a good example for your question. It can easily be achieved with sum, you may want to provide some different types of examples. Commented Apr 28, 2012 at 18:33
  • 27
    Hey JBernardo - Summing over a list of numbers was meant as a rather degenerate example, I'm more interested in the general idea of accumulating the elements of a list using some binary operation, and a starting value, not summing integers specifically. Commented Apr 28, 2012 at 18:43
  • 1
    @mistertim: sum() actually provides limited functionality with this. sum([[a], [b, c, d], [e, f]], []) returns [a, b, c, d, e, f] for example. Commented Apr 28, 2012 at 19:34
  • Although the case of doing it with lists is a good demonstration of things to watch for with this technique - + on lists is a linear time operation in both time and memory, making the whole call quadratic. Using list(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 to list to make it constant in terms of memory. Commented May 21, 2013 at 9:48