Powerset—How to Get All Combinations of a List in Python

Forming all combinations of a list in python

To find the combinations of length r in a Python list, use itertools.combinations() method:

import itertools

combinations = itertools.combinations(list_items, r)

To find all the combinations of a Python list, also known as a powerset, follow these steps:

  1. Import the built-in itertools module.
  2. Specify a list of items.
  3. Initialize an empty list for storing the combinations.
  4. Create a loop that loops values from 0 to the length of the list + 1.
  5. Create an inner loop that adds combinations of length r to the list of combinations.

Here is how it looks in the code:

import itertools

numbers = [1, 2, 3]

combinations = []

for r in range(len(numbers)+1):
    for combination in itertools.combinations(numbers, r):
        combinations.append(combination)

print(combinations)

Output:

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

How to Get All Combinations of Unique Elements in Python

So you want no duplicate values in the list of all the combinations? No problem.

To obtain the unique powerset in Python, convert the list to a set to remove duplicates. Otherwise, use the same approach as above.

Here is how the code looks after the change:

import itertools

numbers = [1, 3, 3]

combinations = []

for r in range(len(numbers)+1):
    for combination in itertools.combinations(set(numbers), r):
        combinations.append(combination)

print(combinations)

Now it only returns the combinations where there are no duplicate values:

[(), (1,), (3,), (1, 3)]

Powerset Recipes—A Simpler and Faster Approach

As per itertools docs, you can use a slightly simpler and perhaps more efficient approach to get all the combinations of an iterable.

Here is the code:

from itertools import chain, combinations

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

numbers = [1, 2, 3]

print(list(powerset(numbers)))

Output:

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

Powerset Recipes—Find All Combinations of Unique Elements

To find all the combinations of unique values, you need to make a tiny change to the above powerset() function. Namely, convert the iterable items to a set to remove the duplicates.

Here is how the code looks now with an example call:

from itertools import chain, combinations

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

numbers = [3, 1, 3]

print(list(powerset(numbers)))

Output:

[(), (1,), (3,), (1, 3)]

Conclusion

Today you learned how to obtain all the combinations of a Python list. This group of sets is also known as the powerset of a list.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading