Iteration Tools (itertools)
In data science, we often need to build complex combinations, cycle infinitely through datasets, or group items efficiently. Python's built-in itertools library provides highly optimized, C-implemented iterator building blocks that are incredibly memory efficient.
1. Cartesian Product (itertools.product)
itertools.product generates the Cartesian product of input iterables, equivalent to nested for loops but executed extremely fast and using minimal memory.
Industry Example: Clothing Inventory Combinations
Suppose an e-commerce platform needs to generate all possible size and color SKU combinations:
import itertools
sizes = ["S", "M", "L"]
colors = ["Red", "Blue", "Black"]
# Create Cartesian product
skus = list(itertools.product(sizes, colors))
print("All Combinations:")
for sku in skus:
print(sku)Output:
All Combinations:
('S', 'Red')
('S', 'Blue')
('S', 'Black')
('M', 'Red')
...2. Permutations & Combinations
In analytics, statistical calculations frequently require selection subsets:
permutations(iterable, r): Generates all -length ordered tuples where order matters.combinations(iterable, r): Generates all -length unique subsets where order does not matter.
import itertools
candidates = ["Alice", "Bob", "Charlie"]
# 1. Permutations: Order matters (e.g., electing President and Vice President)
print("Permutations (length 2):")
print(list(itertools.permutations(candidates, 2)))
# 2. Combinations: Order doesn't matter (e.g., selecting a committee of 2)
print("\nCombinations (length 2):")
print(list(itertools.combinations(candidates, 2)))3. Infinite Generators (itertools.cycle & itertools.count)
itertools.count(start, step): Returns an infinite arithmetic sequence of numbers.itertools.cycle(iterable): Loops infinitely through the elements of an input sequence.
import itertools
# Safe count demo with a break condition
for number in itertools.count(start=5, step=5):
if number > 20:
break
print(number) # Prints: 5, 10, 15, 20Hands-on Exercises
Exercise 1: Generate a Deck of Cards
Generate a standard set of cards combining 2 suits ["Hearts", "Spades"] and 3 ranks ["Ace", "King", "Queen"] using itertools.product().
# Write your code below and click Run CodeClick to view Answer
import itertools
suits = ["Hearts", "Spades"]
ranks = ["Ace", "King", "Queen"]
deck = list(itertools.product(ranks, suits))
print(deck)
# Output: [('Ace', 'Hearts'), ('Ace', 'Spades'), ('King', 'Hearts'), ('King', 'Spades'), ('Queen', 'Hearts'), ('Queen', 'Spades')]