Skip to content Skip to sidebar Skip to footer

Itertools Vs Nested Loops Performance

I have to generate all the 2-pair combinations of items in a list. Now, I know of two ways to accomplish this: nested for-loops, and python's built-in itertools: from itertools imp

Solution 1:

So I went ahead and used Python's timeit to measure the runtimes, modifying the first loop as @user2357112 suggested:

import timeit
from itertools importcombinationsfoo= [i for i in xrange(0, 1000)]    

def loop_test():
    combos = []
    for i in xrange(len(foo)):
        for j in xrange(i + 1, len(foo)):
            combos.append((foo[i], foo[j]))    

def iter_test():
    combos = []
    for c in combinations(foo, 2):
        combos.append(c)    

if__name__== '__main__':
    print timeit.timeit('loop_test()', setup='from __main__ import loop_test', number=1000)
    print timeit.timeit('iter_test()', setup='from __main__ import iter_test', number=1000)

With an output:

59.1836869717
45.6625859737

Interestingly, it appears as though itertools is in fact faster than the nested loops.

Post a Comment for "Itertools Vs Nested Loops Performance"