Categories
Python Answers

How to get all possible combinations of a list’s elements with Python?

Spread the love

Sometimes, we want to get all possible combinations of a list’s elements with Python.

In this article, we’ll look at how to get all possible combinations of a list’s elements with Python.

How to get all possible combinations of a list’s elements with Python?

To get all possible combinations of a list’s elements with Python, we can use the itertools.combinations method.

For instance, we write:

import itertools

stuff = [1, 2, 3]
for L in range(0, len(stuff) + 1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

We loop through number ranges from 0 to len(stuff) + 1.

In the loop body, we get the combination of stuff when we choose L items with itertools.combinations.

And then we loop through the returned iterator with another for loop.

In the loop body, we print the subset of items from stuff that are chosen, which are stored in a tuple.

Therefore, we see:

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

printed.

Conclusion

To get all possible combinations of a list’s elements with Python, we can use the itertools.combinations method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *