A Comprehensive Guide for Beginners and Experts

This tutorial will provide you with an in-depth understanding of how to get all combinations of a list. It uses itertools library functions which are essential tools for working with lists. …

Updated October 2, 2023

This tutorial will provide you with an in-depth understanding of how to get all combinations of a list. It uses itertools library functions which are essential tools for working with lists.

  1. Introduction to the Problem: We all have some list of items that we would like to generate all possible combinations of, perhaps to run tests on or to analyze in some other way. In Python, you can use itertools module functions to efficiently get all such combinations.

  2. Combinations and Permutations: The major difference between combinations and permutations is that combinations do not consider the order while permutation does. Let’s discuss about combinations first. You can generate combinations of any given list using itertools.combinations() function in python as shown below:

import itertools

# Define a list
my_list = [1, 2, 3]

# Get all combinations of length 2
all_combs = list(itertools.combinations(my_list, 2))
for comb in all_combs:
    print(comb)

In the above example, we get the combinations of a list [1, 2, 3] with length 2 i.e. (1, 2), (1, 3), (2, 3). The output will be in tuples.

  1. Recursive Combinations: To generate all combinations of elements at each level, we can use the itertools.product() function which generates the cartesian product of input iterables.
# Get all recursive combinations of length 2
rec_combs = list(itertools.product(my_list, repeat=2))
for comb in rec_combs:
    print(comb)

In this example, we get the cartesian product or combination of a list [1, 2, 3] with length 2 i.e. (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3). The output will be in tuples.

  1. Handling Duplicate Combinations: By default, the itertools functions don’t consider duplicate elements while generating combinations/permutations. But if you want to get all possible combinations of a list irrespective of their order and without considering duplicates, we can use combinations_with_replacement() function in itertools as shown below:
# Get all combinations with replacement of length 2
dup_combs = list(itertools.combinations_with_replacement(my_list, 2))
for comb in dup_combs:
    print(comb)

In the above example, we get the combinations (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3). The output will be in tuples.

  1. Conclusion: The itertools module functions are very powerful when it comes to dealing with lists and combinations of elements. They make the process of generating all possible combinations easy.
Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!