Search code examples
pythoncombinationscombinatoricscartesian-product

While generating all possible combinations itertools.combinations_with_replacement() vs itertools.product()?


While writing a program that finds all the different combos for a list, I found a lot of threads about using intertools.product() instead of intertools.combinations_with_replacement(), as I have been doing. No one explained why you should use intertools.product. I would love to know how this affects my program output.


Solution

  • From Python documentation

    itertools.product(*iterables[, repeat])

    Cartesian product of input iterables.

    Equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

    In other words:

    for x, y in itertools.product(A, B):
    

    replaces

    for x in A:
        for y in B:
    ............
    

    EDIT:

    • itertolls.combinations_with_replacement() will take single iterable and produce all possible combinations of its elements of given length;

    • itertools.product() will produce combination of values from several iterables, where element 0 of the resulting tuple is from the first iterable, element 1 - from second, etc.