Teknophilia
Teknophilia

Reputation: 778

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 import combinations

foo = [1, 2, 3, 4]

for i in xrange(len(foo)):
    for j in xrange(i + 1, len(foo)):
        print foo[i], foo[j]

for c in  combinations(foo, 2):
    print c

My question is: are there any significant advantages to using one over the other?

Upvotes: 3

Views: 4917

Answers (1)

Teknophilia
Teknophilia

Reputation: 778

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

import timeit
from itertools import combinations

foo = [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.

Upvotes: 7

Related Questions