How to generate combinations in Python with itertools

Generate all unique combinations of r items from a given list using itertools.combinations.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

12 lines
Python 3.9+
import itertools

def combinations_generator(items, r):
    return list(itertools.combinations(items, r))

if __name__ == "__main__":
    items = ['A', 'B', 'C', 'D']
    r = 2
    result = combinations_generator(items, r)
    for combo in result:
        print(combo)
    print(f"Total: {len(result)} combinations of {r} from {len(items)} items")

Output

stdout
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
Total: 6 combinations of 2 from 4 items

How it works

The itertools.combinations function returns an iterator that yields tuples of length r from the input iterable. It treats the input as ordered but ignores the order of elements within each combination, so ('A','B') and ('B','A') count as the same combination and are not both produced. Converting the iterator to a list with list() materializes all combinations at once, which is fine for small inputs but memory-heavy for large sets. The function uses the lexicographic order of the input items to determine combination ordering, so passing a sorted list gives predictable output.

Common mistakes

  • Confusing combinations with permutations — combinations ignore order, permutations do not.
  • Passing an integer instead of an iterable to `itertools.combinations`, which raises a TypeError.
  • Forgetting that the result is a tuple iterator, so you must iterate or convert it to a list to see the values.
  • Using `r` larger than the length of the input, which returns an empty list.

Variations

  1. Use `itertools.combinations_with_replacement(items, r)` to allow the same item to appear more than once.
  2. Generate combinations as a generator expression instead of a list to save memory: `(combo for combo in itertools.combinations(items, r))`.

Real-world use cases

  • Building feature pairs for a recommender system where each pair of items is tested together.
  • Generating all possible team pairings from a roster for scheduling practice matches.
  • Testing combinations of configuration flags in an experiment framework to find valid parameter sets.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.