import itertools ################ case 1 a = [[1, 2], [3, 4], [5, 6]] print list(itertools.chain.from_iterable(a)) %timeit -n 10000 list(itertools.chain.from_iterable(a)) print sum(a, []) %timeit -n 10000 sum(a, []) print [x for l in a for x in l] %timeit -n 10000 [x for l in a for x in l]
# result: # [1, 2, 3, 4, 5, 6] # 10000 loops, best of 3: 801 ns per loop # [1, 2, 3, 4, 5, 6] # 10000 loops, best of 3: 359 ns per loop # [1, 2, 3, 4, 5, 6] # 10000 loops, best of 3: 371 ns per loop
################ case 2 b = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] [x for l1 in b for l2 in l1 for x in l2] # [1, 2, 3, 4, 5, 6, 7, 8]
################ case 3 a = [1, 2, [3, 4], [[5, 6], [7, 8]]] flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x] flatten(a) # [1, 2, 3, 4, 5, 6, 7, 8]