Hi All,

I wanna generate all possible combination of certain list using python.

For Example I have a list like

``````list = ['A','B','C']
``````

I wanna generate all possible combination of these list elements like using "itertools":

``````AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
``````

Thanks!

6
Contributors
7
Replies
12
Views
6 Years
Discussion Span
Last Post by pyTony

You can do triple for loop, one for each letter.

Here is a way using my snippet on non recursive tree traversal 1.4

``````from functools import partial
import walktree as wt

def subn(letters, k, node):
if len(node) == k:
return
for x in letters:
yield node + x

for path in wt.walk("", partial(subn, "ABC", 3), wt.event(wt.leaf)):
print path[-1]

"""my output -->
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
"""
``````

Nice creativity

thanks

Technically you want a selection **which allows sequence items to be repeated,
a **combination
or permutation does not:

``````def selections(seq, n):
"""
selections(seq, n) is a recursive generator where
seq is an iterable object
n is the sample size
n = len(seq) is the max sample size
returns a list of lists of unique sample size items
"""
if n == 0:
yield []
else:
for i in range(len(seq)):
# recursion
for ss in selections(seq, n - 1):
yield [seq[i]] + ss

# use 'ABC' or ['A', 'B', 'C']
iterable = 'ABC'
sample_size = len(iterable)
sel = list(selections(iterable, sample_size))

# show as strings
for item in sel:
s = "".join(item)
print(s)

""" my result >>>
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
"""
``````

itertools.product will also do this.

``````import itertools
import pprint

letters = ['A', 'B', 'C']
pprint.pprint(list(itertools.product(letters, repeat=3)))

"""Output-->
[('A', 'A', 'A'),
('A', 'A', 'B'),
('A', 'A', 'C'),
('A', 'B', 'A'),
('A', 'B', 'B'),
('A', 'B', 'C'),
('A', 'C', 'A'),
('A', 'C', 'B'),
('A', 'C', 'C'),
('B', 'A', 'A'),
('B', 'A', 'B'),
('B', 'A', 'C'),
('B', 'B', 'A'),
('B', 'B', 'B'),
('B', 'B', 'C'),
('B', 'C', 'A'),
('B', 'C', 'B'),
('B', 'C', 'C'),
('C', 'A', 'A'),
('C', 'A', 'B'),
('C', 'A', 'C'),
('C', 'B', 'A'),
('C', 'B', 'B'),
('C', 'B', 'C'),
('C', 'C', 'A'),
('C', 'C', 'B'),
('C', 'C', 'C')]
"""
``````

Edited by snippsat

snippsat,

very nice discovery

``````letters = list('ABC')
for a in letters:
for b in letters:
for c in letters:
print(a+b+c)
``````

Other point is that these are not combinations but permutations with repeat.

Edited by pyTony