0

The thing i'm trying to do is to create every single combination, but only using one of each letter

I did it with 3 sets of letters

inlist = ["Aa", "Bb", "Cc"]
outlist = []

for i in inlist[0]:
    for j in inlist[1]:
        for k in inlist[2]:
            outlist.append(str(i + j + k))

Output: outlist = ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']

What if i want to do this with 2 or 4 sets of letters? Is there an easier way?

2 Answers2

1

itertools.product does exactly that:

from itertools import product

inlist = ["Aa", "Bb", "Cc"]
outlist = []

for abc in product(*inlist):
    outlist.append(''.join(abc))

print(outlist)
# ['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']

abc is a tuple going from ('A', 'B', 'C') to ('a', 'b', 'c'). the only thing left to to is join that back to a string with ''.join(abc).

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0
>>> import itertools
>>> inlist = ["Aa", "Bb", "Cc"]
>>> [''.join(i) for i in itertools.product(*inlist)]
['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']
dodopy
  • 159
  • 5