why sum on lists is (sometimes) faster than itertools.chain?

Your test inputs are tiny. At those scales, the horrific O(n^2) asymptotic runtime of the sum version isn’t visible. The timings are dominated by constant factors, and sum has a better constant factor, since it doesn’t have to work through iterators.

With bigger lists, it becomes clear that sum is not at all designed for this kind of thing:

>>> timeit.timeit('list(itertools.chain.from_iterable(l))',
...               'l = [[i] for i in xrange(5000)]; import itertools',
...               number=1000)
0.20425895931668947
>>> timeit.timeit('sum(l, [])', 'l = [[i] for i in xrange(5000)]', number=1000)
49.55303902059097

Leave a Comment