Search code examples
pythonpython-3.xcombinationsfor-in-loop

Python itertools.combinations early cutoff


In the following code,the only item that is printed from object 'c' in the looped product is the first one, although both 'c' and 'd' contain 3 items and all 3 items of 'd' are iterated over properly.

from itertools import combinations

c,d = combinations(map(str, range(3)),2), combinations(map(str, range(3)),2)
for x in c:
 for y in d:
  print(x,y)

Typecasting generators to list solves this problem and prints 9 lines but why does this occur in the first place?


Solution

  • The problem is that c and d are both iterators, and after the first time through the inner loop, d has been exhausted. The simplest way to fix this is to do:

    from itertools import combinations, product
    
    c = combinations(map(str, range(3)),2)
    d = combinations(map(str, range(3)),2)
    
    for x, y in product(c, d):
        print(x,y)
    

    This produces:

    ('0', '1') ('0', '1')
    ('0', '1') ('0', '2')
    ('0', '1') ('1', '2')
    ('0', '2') ('0', '1')
    ('0', '2') ('0', '2')
    ('0', '2') ('1', '2')
    ('1', '2') ('0', '1')
    ('1', '2') ('0', '2')
    ('1', '2') ('1', '2')