How to Get All Combinations of a List in Python
Generate and display all combinations of a given length from a list using Python's itertools.combinations.
Python code
16 linesfrom itertools import combinations
def list_combinations(items, r):
"""Return all combinations of length r from a list."""
return list(combinations(items, r))
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry", "date"]
pick = 2
result = list_combinations(fruits, pick)
print(f"List: {fruits}")
print(f"Choosing {pick} at a time:")
for combo in result:
print(combo)
print(f"Total combinations: {len(result)}")
Output
List: ['apple', 'banana', 'cherry', 'date']
Choosing 2 at a time:
('apple', 'banana')
('apple', 'cherry')
('apple', 'date')
('banana', 'cherry')
('banana', 'date')
('cherry', 'date')
Total combinations: 6
How it works
itertools.combinations yields tuples of the requested length without repeating elements and without regard to order. The function wraps the iterator in list() so you can inspect or reuse the results directly. Because combinations are emitted in lexicographic order based on the input, output is deterministic and easy to reason about. This is a standard-library solution, so no third-party imports are needed, making it efficient and dependency-free for production code.
Common mistakes
- Confusing combinations with permutations — combinations ignore order, permutations do not.
- Passing r larger than the list length, which returns an empty list instead of an error.
- Forgetting to convert the iterator to a list when you need to index or slice the results.
Variations
- Use `itertools.permutations` if you need ordered selections (arrangements).
- Use `itertools.combinations_with_replacement` to allow the same item to appear multiple times.
Real-world use cases
- Generating all possible team pairings for a scheduling or tournament application.
- Creating feature combinations for A/B testing configurations in an experimentation platform.
- Enumerating subset combinations during a brute-force search in an algorithmic trading backtester.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.