sum([a, b, c], d)
produces d + a + b + c
.
In your example, a
, b
, c
, and d
are [1, 2]
, [3, 4]
, [5, 6]
, and []
.
sum([[1, 2], [3, 4], [5, 6]], [])
produces [] + [1, 2] + [3, 4] + [5, 6]
, which is [1, 2, 3, 4, 5, 6]
because +
is concatenation for lists.
This is absurdly inefficient, because every +
operation involved requires copying all the data from each of its arguments:
In [7]: x = [[i] for i in range(30000)]
In [8]: %timeit sum(x, [])
1 loop, best of 3: 2.06 s per loop
In [9]: %timeit [elem for sublist in x for elem in sublist]
1000 loops, best of 3: 1.91 ms per loop
sum(x, [])
takes quadratic time, whereas a more efficient implementation takes linear time. Never do sum(x, [])
.