All Combinations For A List Of Objects

Generating all combinations for a list of objects is a common operation in Python. The itertools module provides efficient built-in methods like combinations() and product() to generate different types of combinations from list objects.

Using itertools.combinations()

The combinations() method generates all possible combinations of a specified length without repetition. It's perfect for mathematical combinations where order doesn't matter and elements can't repeat.

Syntax

itertools.combinations(iterable, length)

Where iterable is the input sequence and length is the size of each combination.

Example 1: Basic Combinations

Generate all combinations of different lengths from a list ?

import itertools

def get_all_combinations(lst):
    combinations_list = []
    for r in range(1, len(lst) + 1):
        combinations_list.extend(itertools.combinations(lst, r))
    return combinations_list

objects = ['A', 'B', 'C']
all_combinations = get_all_combinations(objects)
print("All combinations:", all_combinations)
All combinations: [('A',), ('B',), ('C',), ('A', 'B'), ('A', 'C'), ('B', 'C'), ('A', 'B', 'C')]

Example 2: Fixed Length Combinations

Generate combinations of a specific length only ?

import itertools

numbers = [1, 2, 3, 4]
combinations_of_2 = list(itertools.combinations(numbers, 2))
print("Combinations of length 2:", combinations_of_2)
Combinations of length 2: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Using itertools.product()

The product() method generates the Cartesian product, allowing repetition of elements. It's useful when you need combinations with replacement.

Syntax

itertools.product(iterable, repeat=r)

Example 3: Combinations with Repetition

Generate all combinations allowing repeated elements ?

import itertools

def get_combinations_with_repetition(lst):
    combinations_list = []
    for r in range(1, len(lst) + 1):
        combinations_list.extend(itertools.product(lst, repeat=r))
    return combinations_list

objects = ['X', 'Y']
all_combinations = get_combinations_with_repetition(objects)
print("Combinations with repetition:", all_combinations)
Combinations with repetition: [('X',), ('Y',), ('X', 'X'), ('X', 'Y'), ('Y', 'X'), ('Y', 'Y'), ('X', 'X', 'X'), ('X', 'X', 'Y'), ('X', 'Y', 'X'), ('X', 'Y', 'Y'), ('Y', 'X', 'X'), ('Y', 'X', 'Y'), ('Y', 'Y', 'X'), ('Y', 'Y', 'Y')]

Comparison

Method Repetition Allowed? Order Matters? Best For
combinations() No No Mathematical combinations
product() Yes Yes Cartesian products with repetition

Conclusion

Use itertools.combinations() for traditional combinations without repetition. Use itertools.product() when you need combinations with repetition allowed. Both methods are memory-efficient and provide clean, readable solutions for generating list combinations.

Updated on: 2026-03-27T09:14:28+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements