How to find all combinations from a list of elements in python ?

Published: July 29, 2020

Tags: Python;

DMCA.com Protection Status

Examples of how to find all combinations from a list in python:

Create a liste

Let's consider the following list:

L = ['a','b','c','d']

of length len(L) = 4

Find all combinations of size 2

To find all combinations of size 2, a solution is to use the python module called itertools

from itertools import combinations

for i in combinations(L,2):
    print(i)

gives

('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')

It is also possible to store the above result in a list:

c2 = [i for i in combinations(L,2)]

print(c2)

returns

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

Find all combinations of size 3

Another example of how to find all combinations of size 3

c3 = [i for i in combinations(L,3)]

print(c3)

returns

[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

Find all combinations

Then to find all combinations just do

comb = []
for n in range(0,len(L)+1):
    comb.append([i for i in combinations(L,n)])

comb

which returns

[[()],
 [('a',), ('b',), ('c',), ('d',)],
 [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')],
 [('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')],
 [('a', 'b', 'c', 'd')]]

Find combinations with replacement

Note: to find combinations with replacement use the function combinations_with_replacement. Example with combinations of size 2 with replacement:

from itertools import combinations_with_replacement

for i in combinations_with_replacement(L,2):
    print(i)

returns

('a', 'a')
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'b')
('b', 'c')
('b', 'd')
('c', 'c')
('c', 'd')
('d', 'd')

References