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.