I answered a few questions here, using this to “flatten” the list of lists:
>>> l = [[1,2,3],[4,5,6],[7,8,9]] >>> sum(l,[])
It works fine and gives:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
although I was told that the sum statement has a = a + b , which is not as efficient as itertools.chain
My planned question is “Why is this possible on lists where it is prevented for strings”, but I did a quick test on my machine comparing sum and itertools.chain.from_iterable using the same data:
import itertools,timeit print(timeit.timeit("sum(l,[])",setup='l = [[1,2,3],[4,5,6],[7,8,9]]')) print(timeit.timeit("list(itertools.chain.from_iterable(l))",setup='l = [[1,2,3],[4,5,6],[7,8,9]]'))
I have done this several times, and I always get roughly the same numbers as shown below:
0.7155522836070246 0.9883352857722025
To my surprise, chain - recommended by sum for lists by everyone in the few comments to my answers - is much slower.
This is still interesting when repeating in a for loop, because it does not actually create a list, but when creating a list, sum wins.
So, you should discard itertools.chain and use sum when the expected result is list ?
EDIT: thanks to some comments, I did another test, increasing the number of lists
s = 'l = [[4,5,6] for _ in range(20)]' print(timeit.timeit("sum(l,[])",setup=s)) print(timeit.timeit("list(itertools.chain.from_iterable(l))",setup=s))
now I get the opposite:
6.479897810702537 3.793455760814343