HOWTO · Python

How to Get All Combinations of a List in Python

This tutorial demonstrates how to get all the combinations of a list's elements in Python.

On this page

Use itertools.combinations() to select a fixed number of items without reusing an input position. If a position may be selected more than once, use itertools.combinations_with_replacement(). Both functions produce combinations, where selection order does not create a new result; permutations treat different orders as distinct.

Choose the right kind of combination

Choose a fixed selection size with combinations(), allow a position to repeat with combinations_with_replacement(), or generate every subset with a powerset() function. The standard-library functions return iterators of tuples. Their input is read by position, so repeated values at different positions can produce duplicate-looking tuples. Result order follows the order of the input positions; the values inside each tuple are not sorted automatically. For a custom rule, recursion can make the selection process explicit.

Use itertools.combinations() for selections without replacement

itertools.combinations(iterable, r) yields tuples of length r and does not reuse a position. The iterable is consumed in its input order. Convert the iterator to a list when you need to store or inspect all results at once; otherwise, iterate over it directly.

Run this example:

from itertools import combinations

items = ["red", "blue", "green"]
for pair in combinations(items, 2):
    print(pair)

The two-item results use each position at most once. To request individual items, set r to 1; to request the entire input as one tuple, set it to the number of input positions. If r exceeds the number of positions, the iterator has no results.

Use itertools.combinations_with_replacement() when selections may repeat

Use itertools.combinations_with_replacement(iterable, r) when selecting the same input position more than once is allowed. It also yields tuples of length r, with the same positional ordering rule. For example, choosing pairs from ["red", "blue"] includes ("red", "red") and ("blue", "blue"); combinations() would omit those pairs. This is useful when a repeated choice is meaningful, such as selecting two scoops when both can use the same flavor. The argument r still controls the length of every tuple.

Use recursion or a generator for a custom implementation

A recursive backtracking function can build results in a list. At each step, it appends one value, recurses from the next position, then removes that value so the loop can try another choice. A generator follows the same selection logic but yields each result as it is found. It avoids retaining the full result collection unless the caller explicitly converts it to a list; it is not inherently faster.

Both custom functions below require r to be a nonnegative integer and raise ValueError otherwise. With r = 0, each returns the single empty tuple; when r is positive but greater than the number of input positions, neither produces a result. The generator checks its argument when iteration begins, because generator function bodies run lazily.

def get_combinations(items, r):
    if not isinstance(r, int) or isinstance(r, bool) or r < 0:
        raise ValueError("r must be a nonnegative integer")

    results = []

    def backtrack(start, chosen):
        if len(chosen) == r:
            results.append(tuple(chosen))
            return
        for index in range(start, len(items)):
            chosen.append(items[index])
            backtrack(index + 1, chosen)
            chosen.pop()

    backtrack(0, [])
    return results


def generate_combinations(items, r):
    if not isinstance(r, int) or isinstance(r, bool) or r < 0:
        raise ValueError("r must be a nonnegative integer")
    if r == 0:
        yield ()
        return
    for index in range(len(items)):
        for suffix in generate_combinations(items[index + 1 :], r - 1):
            yield (items[index],) + suffix


items = ["red", "blue", "green"]
print(get_combinations(items, 2))
print(list(generate_combinations(items, 2)))

For a lazy custom version, use yield at the point where a complete selection is reached. In either implementation, advance the next recursive call to index + 1 to avoid reusing a position. If duplicate values are present, outputs can look identical even though they came from separate positions.

Generate every subset with a powerset() function

A powerset contains subsets of every size, including the empty tuple and the full input. This implementation combines the results for each possible size. chain.from_iterable() returns an iterator, so wrap it in list() only when all subsets need to be materialized.

from itertools import chain, combinations


def powerset(items):
    values = list(items)
    return chain.from_iterable(
        combinations(values, size) for size in range(len(values) + 1)
    )


for subset in powerset(["red", "blue"]):
    print(subset)

For n input positions, a powerset has 2**n subsets. That count grows quickly, so prefer a fixed-size combinations iterator when the task only needs selections of one size. Use the powerset when subsets of all sizes are actually part of the result.