I've got a list such as [[1,2], [3,4], [5,6], [7,8], [9,10]]
. I want to get [1,2,3,4,5,6,7,8,9,10]
.
This question gives some very good options for flattening lists in general. The answers given there work with variable length sublists. Here though, I know that every sublist has the same length (in particular length 2).
I'm wondering if it is possible to take advantage of the homogeneous sublist length to improve on the answers given in the question I linked to. In particular, is there anything that will do better at flattening this list than [item for sublist in l for item in sublist]
?
edit: by 'better', I mean faster for a very long list.
edit:
One thing I did not mention - I do not care about the order of the flattened list (but I care about multiplicity)
import timeit
import itertools
def f0():
l=[[1,2]]*99
[item for sublist in l for item in sublist]
def f1():
l=[[1,2]]*99
list(itertools.chain.from_iterable(l))
def f2():
l = [[1,2]]*99
z = map(list,zip(*l))
z[0].extend(z[1])
print timeit.timeit("f0()", setup="from __main__ import f0, f1, f2", number=10000)
print timeit.timeit("f1()", setup="from __main__ import f0, f1, f2", number=10000)
print timeit.timeit("f2()", setup="from __main__ import f0, f1, f2", number=10000)
yields the output
0.13874912262
0.103307008743
0.10813999176
Could my zip
function be done faster?