“Fundamentally, which one is faster? Using the "itertools" module, or using a list comprehension? I'm basically trying to improve my computation speed here.” - @davidadamojr
I've been doing some tests and I find that the code below is actually faster.
list_ = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)] list(sum(list_, ()))
Someone correct me if I'm wrong.
Here are some tests below.
>>> list_ = [(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)] >>> >>> operation_1 = lambda: [tuple_item for tuple_ in list_ for tuple_item in tuple_] >>> def operation_2 (): final_list = [] for tuple_ in list_: for tuple_item in tuple_: final_list.append(tuple_item) return final_list >>> operation_3 = lambda: reduce(list.__add__, map(list, list_)) >>> def operation_4 (): import itertools return list(itertools.chain(*list_)) >>> operation_5 = lambda: list(sum(list_, ())) >>> >>> operation_1() [1, 2, 1, 3, 1, 4, 1, 5, 1, 6] >>> operation_2() [1, 2, 1, 3, 1, 4, 1, 5, 1, 6] >>> operation_3() [1, 2, 1, 3, 1, 4, 1, 5, 1, 6] >>> operation_4() [1, 2, 1, 3, 1, 4, 1, 5, 1, 6] >>> operation_5() [1, 2, 1, 3, 1, 4, 1, 5, 1, 6] >>> >>> import timeit >>> >>> print('operation_1 completed in %s seconds.' % (timeit.timeit(operation_1))) operation_1 completed in 1.57890490223 seconds. >>> print('operation_2 completed in %s seconds.' % (timeit.timeit(operation_2))) operation_2 completed in 2.90350501659 seconds. >>> print('operation_3 completed in %s seconds.' % (timeit.timeit(operation_3))) operation_3 completed in 5.08437990236 seconds. >>> print('operation_4 completed in %s seconds.' % (timeit.timeit(operation_4))) operation_4 completed in 3.85125378138 seconds. >>> print('operation_5 completed in %s seconds.' % (timeit.timeit(operation_5))) operation_5 completed in 1.2623826489 seconds.
[e for l in lst for e in l]" (from David Robinson's answer) is the fastest way to do it, but I think it would be impossible to do this "without [implicitly] actually iterating through the original list of tuples". Even if you use some "built-in function/method", that's what it has to do under-the-hood.