## debasishgang7

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!

## pyTony 888

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

## Gribouillis 1,391

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
"""

## redbottom52 13

Nice creativity

commented: thanks +13

## Lardmeister 461

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
"""

## snippsat 661

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')]
"""

## Lardmeister 461

snippsat,

very nice discovery