How to Find all Combinations of a list in Python
In this tutorial, we will learn how to create a list of tuples containing every possible combination from another list in Python.
To find all the possible combinations for a list in Python, loop through the list and use the itertools.combinations()
function.
import itertools
items = [1,2,3,4]
combinations = []
for r in range(len(items) + 1):
combinations_obj = itertools.combinations(items, r)
combinations_list = list(combinations_obj)
combinations += combinations_list
print(combinations)
[(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)]