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!

Recommended Answers

All 7 Replies

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

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

snippsat,

very nice discovery

As you gave ready answers, let's spell out this obvious answer (this is abandoned thread anyway, OP visitted last 2 days ago):

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.