Will Stuyvesant wrote:
data = [['foo','bar','baz'],['my','your'],['holy','grail']]
sum(data, [])
['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
The second parameter passed to sum is just to overrride default initial value "zero".
It's worth keeping in mind that this solution has the same efficiency problems that a loop that =+ strings does:
> python -m timeit -s "data = [range(10) for _ in range(100)]" "sum(data, [])"
1000 loops, best of 3: 530 usec per loop
> python -m timeit -s "data = [range(10) for _ in range(100)]" "[w for d in data for w in d]"
10000 loops, best of 3: 151 usec per loop
> python -m timeit -s "data = [range(10) for _ in range(1000)]" "sum(data, [])"
10 loops, best of 3: 54.2 msec per loop
> python -m timeit -s "data = [range(10) for _ in range(1000)]" "[w for d in data for w in d]"
100 loops, best of 3: 1.75 msec per loop
The sum function used in this way (or a loop with a +=) is O(N**2) while the LC is O(N).
Steve -- http://mail.python.org/mailman/listinfo/python-list