+1 vote
in Programming Languages by (51.8k points)
I have a list containing "n" elements and I want to create all possible combinations of elements by selecting 1..n elements from the list. Is there any Python module that I can use for it?

1 Answer

+2 votes
by (281k points)
selected by
 
Best answer

You can generate all possible combinations of elements by selecting 1...n elements from a list of n elements using Python's itertools.combinations module. The combinations() function takes the "list" and "number of elements" you want to select as arguments. It returns an object that you need to cast to a list to get the list.

Here is an example:

>>> from itertools import combinations
>>> a = [1, 2, 3, 4, 5]
>>> combs=[]
>>> for i in range(len(a)):
...     v = combinations(a, i+1)
...     combs.append(list(v))
...
>>> combs
[[(1,), (2,), (3,), (4,), (5,)], [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)], [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)], [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)], [(1, 2, 3, 4, 5)]]
 


...