Python small brute-forcer I have 20+ key set. Keyset is like:

Key[0] = { "PossibleKey0", "PossibleKey0Another", "AnotherPossibleKey0" }
Key[1] = { ....


There is an encryption which needs to be broken, it will receive 20+ keys, one after another. So it applies decryption one-by-one.

So key[0] has 3 different possible keys, same for key[1], key[2], etc.

I should try each key with its each possible keys. I decided to write it like:

for i in range(0, len(Key[0])):
    for j in range(0, len(Key[1])):
        for k in range(0, len(Key[2])):
            for l in range(0, len(Key[2])):
                Decrypt(Key[0][i], Key[1][j], Key[2][k], Key[3][l])


But it looks OK for small key sets, what's better approach when there will be 20+ keys?
In general, you can use itertools.product to factor out nested loops, and tuple unpacking with * to neatly deal with multiple arguments:

from itertools import product

for keys in product(*Key):
    Decrypt(*keys)


A simple example:

&gt;&gt;&gt; from itertools import product
&gt;&gt;&gt; keys = ["ab", "cd", "ef", "gh"]
&gt;&gt;&gt; for k in product(*keys):
    print k


('a', 'c', 'e', 'g')
('a', 'c', 'e', 'h')
('a', 'c', 'f', 'g')
('a', 'c', 'f', 'h')
('a', 'd', 'e', 'g')
('a', 'd', 'e', 'h')
('a', 'd', 'f', 'g')
('a', 'd', 'f', 'h')
('b', 'c', 'e', 'g')
('b', 'c', 'e', 'h')
('b', 'c', 'f', 'g')
('b', 'c', 'f', 'h')
('b', 'd', 'e', 'g')
('b', 'd', 'e', 'h')
('b', 'd', 'f', 'g')
('b', 'd', 'f', 'h')


Note that for four sets of 20 keys, there would be 160,000 combinations (20 ** 4 == 160000).