87. Python’s itertools Module
1. Counting with itertools.count
import itertools
# Create an infinite counter starting from 0
counter = itertools.count(start=0, step=2)
# Print the first 5 numbers from the counter
for i in itertools.islice(counter, 5):
print(i)2. Generating Permutations with itertools.permutations
import itertools
# Generate all permutations of a list of 3 items
items = ['A', 'B', 'C']
permutations = itertools.permutations(items)
# Print the permutations
for perm in permutations:
print(perm)3. Generating Combinations with itertools.combinations
4. Cartesian Product with itertools.product
5. Infinite Cycling with itertools.cycle
6. Repeating Elements with itertools.repeat
7. Chaining Iterables with itertools.chain
8. Filtering Iterables with itertools.compress
9. Grouping Elements with itertools.groupby
10. Taking a Slice of an Iterable with itertools.islice
Last updated