Eplox Eplox - 3 months ago 15
Python Question

Python: Avoid using multiple nested for loops to iterate over strings

Is there a simpler way to iterate over multiple strings than a massive amount of nested for loops?

list = ['rst','uvw','xy']

for x in list[0]:
for y in list[1]:
for z in list[2]:
print x+y+z

rux
ruy
...
tvx
tvy
twx
twy


Example list I really want to avoid typing writing loops for:

list = ['rst','uvw','xy','awfg22','xayx','1bbc1','thij','bob','thisistomuch']

Answer

You need itertools.product:

import itertools
list = ['rst','uvw','xy','awfg22','xayx','1bbc1','thij','bob','thisistomuch']
for x in itertools.product(*list):
    print(''.join(x))

product returns all possible tuples of elements from iterators it gets. So

itertools.product('ab', 'cd')

will return a generator, yielding ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')