Search code examples
pythonloopsfor-loopnested-loops

Is there a way to make a nested loop with as many loops as you like (python)?


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?


Solution

  • 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).