Preliminary
A handful of excellent resources exist for learning what functions are available in the itertools
module. The docs themselves are a great place to start.
The thing about itertools
, though, is that it is not enough to just know the definitions of the functions it contains. The real power lies in composing these functions to create fast, memory-efficient, and good-looking code.
This article takes a different approach. Rather than introducing itertools
to you one function at a time, you will construct practical examples designed to encourage you to “think iteratively.” In general, the examples will start simple and gradually increase in complexity.
# Import combinations with replacements from itertools
from itertools import combinations_with_replacement
Create a list of objects
# Create a list of objects to combine
list_of_objects = ['warplanes', 'armor', 'infantry']
Find all combinations (with replacement) for the list
# Create an empty list object to hold the results of the loop
combinations = []
# Create a loop for every item in the length of list_of_objects, that,
for i in list(range(len(list_of_objects))):
# Finds every combination (with replacement) for each object in the list
combinations.append(combinations_with_replacement(list_of_objects, i+1))
[<itertools.combinations_with_replacement at 0x7f85d03c6408>,
<itertools.combinations_with_replacement at 0x7f85d03c6458>,
<itertools.combinations_with_replacement at 0x7f85d03c64a8>]
# Flatten the list of iterators into a single list
combinations = [i for row in combinations for i in row]
# View the results
combinations
[('warplanes',),
('armor',),
('infantry',),
('warplanes', 'warplanes'),
('warplanes', 'armor'),
('warplanes', 'infantry'),
('armor', 'armor'),
('armor', 'infantry'),
('infantry', 'infantry'),
('warplanes', 'warplanes', 'warplanes'),
('warplanes', 'warplanes', 'armor'),
('warplanes', 'warplanes', 'infantry'),
('warplanes', 'armor', 'armor'),
('warplanes', 'armor', 'infantry'),
('warplanes', 'infantry', 'infantry'),
('armor', 'armor', 'armor'),
('armor', 'armor', 'infantry'),
('armor', 'infantry', 'infantry'),
('infantry', 'infantry', 'infantry')]