A combinatoric iterator will perform a set of statistical or mathematical operations on an input iterable.
A useful itertool that is a combinatoric iterator is the
combinations() itertool. This itertool will produce an iterator of tuples that contain combinations of all elements in the input.
combinations() itertool takes in two inputs, the first being the input
iterable, and the second being a value
r that represents the length of each combination tuple.
The return type of
combinations() is an iterator, so as before with
chain(), if we want to use the returned object directly, it must be explicitly converted into an iterable type (list, set, dictionary, etc) first.
To show how it’s used, suppose we have a list of even numbers and we want all possible combinations of 2 even numbers:
import itertools even = [2, 4, 6] even_iterator = list(itertools.combinations(even, 2)) print(even_iterator)
- Create the
combinations()iterator with our even numbers list as input and our
rlength as 2, since we want groups of 2 combinations.
- Convert it to a list to directly access the list of tuple combinations.
even_iterator. The result is a list of combination tuples for all 3 list members:[(2, 4), (2, 6), (4, 6)]
Now, let’s try using a combinations itertool within our pet store!
We have another shelving unit to display by the register that can only hold 3 collars. We have a list of collars of varying colors and sizes.
We want to know how many different combinations exist to display a set of 3 collars. Use the
combinations() itertool to do this. Set the returned iterator to a variable named
for loop, print each item in
collar_combo_iterator to see all the possible collar combinations.