W3docs

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

You can use the itertools library in Python to get all possible combinations of a list's elements.

You can use the itertools library in Python to get all possible combinations of a list's elements. Here is a code snippet that demonstrates how to use the itertools.combinations function to get all possible combinations of a given list:

Get all possible combinations of a list’s elements in Python

python— editable, runs on the server

This will output:


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

You can also use itertools.combinations_with_replacement to get all possible combinations of a list's elements with replacement.

Get all possible combinations of a list’s elements in Python with replacement

python— editable, runs on the server

this will output :


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

Note that the second argument of the function specifies the length of the combinations, so itertools.combinations(my_list, 2) returns all possible 2-element combinations of the elements in my_list.