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.
To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.
What does itertools. combinations() do ? It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order.
itertools.combinations(iterable, r)This tool returns the length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With