itertools.combinations() in Python 2026 with Efficient Code
itertools.combinations() is the standard and most efficient way to generate all possible combinations of elements from an iterable. In 2026, it remains one of the most valuable tools in the Python standard library for combinatorial tasks, data analysis, and algorithm development.
This March 15, 2026 guide covers everything you need to know about using itertools.combinations() effectively.
TL;DR — Key Takeaways 2026
combinations(iterable, r)returns all possible r-length combinations- It generates combinations in lexicographic sort order
- Returns an iterator — very memory efficient
- Much faster and cleaner than writing nested loops
- Works with any iterable (lists, strings, tuples, etc.)
1. Basic Usage
from itertools import combinations
team = ["Alice", "Bob", "Carol", "Dave"]
# All possible pairs (r=2)
pairs = list(combinations(team, 2))
print(pairs)
# [('Alice', 'Bob'), ('Alice', 'Carol'), ('Alice', 'Dave'), ('Bob', 'Carol'), ('Bob', 'Dave'), ('Carol', 'Dave')]
# All possible groups of 3
groups = list(combinations(team, 3))
2. Real-World Efficient Patterns in 2026
# 1. Choosing toppings
toppings = ["cheese", "pepperoni", "mushroom", "onion", "sausage"]
for combo in combinations(toppings, 3):
print("Pizza with:", ", ".join(combo))
# 2. With indices
for i, combo in enumerate(combinations(team, 2), start=1):
print(f"Combination {i}: {combo}")
# 3. Converting to list of strings
pairs_str = [f"{a}-{b}" for a, b in combinations(team, 2)]
# 4. Large combinations with lazy iteration
large_set = range(20)
for combo in combinations(large_set, 5):
# Process each combination without loading all into memory
pass
3. Performance Comparison 2026
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| Nested Loops | Poor | Slow | High |
itertools.combinations | Excellent | Very Fast | Low (iterator) |
4. Best Practices with itertools.combinations() in 2026
- Always prefer
combinations()over manual nested loops - Use
enumerate()when you need indices - Keep it lazy — only convert to list when necessary
- Combine with
Counteror other tools for powerful data analysis - Use with large datasets carefully — combinations grow factorially
Conclusion — itertools.combinations() in 2026
itertools.combinations() is the clean, efficient, and Pythonic way to generate combinations. In 2026, replacing manual nested loops with combinations() is considered a basic best practice that improves both performance and code maintainability.
Next steps:
- Replace all manual combination loops in your codebase with
itertools.combinations() - Related articles: The itertools Module in Python 2026 • Efficient Python Code 2026