Search code examples
pythonpython-itertools

How to do dependent nested loop using itertools.product?


for i in range(n):
    for j in range(i + 1, n):

How to do this using itertools.product? It takes a variable number of iterables, but there doesn't seem to be a way to reference one iterable from another.

For example, n=5:

for x in itertools.product(range(5), range(1, 5))

generates

(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 1)
...

Note (1, 1) is not supposed to be there.


Solution

  • For a given n

    n = 5
    
    for i in range(n):
        for j in range(i + 1, n):
            print((i, j))
    

    Prints:

    (0, 1)
    (0, 2)
    (0, 3)
    (0, 4)
    (1, 2)
    (1, 3)
    (1, 4)
    (2, 3)
    (2, 4)
    (3, 4)
    

    This isn't a Cartesian product, which is what itertools.product produces. It is a combination which can be made with itertools.combinations:

    from itertools import combinations, product
    
    tups = list(combinations(range(5), r=2))
    

    tups will be:

    [(0, 1),
     (0, 2),
     (0, 3),
     (0, 4),
     (1, 2),
     (1, 3),
     (1, 4),
     (2, 3),
     (2, 4),
     (3, 4)]