2

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']
0

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly what I was looking for!
3

You are looking for the product function from itertools:

import itertools

lst = ['rst','uvw','xy']
[''.join(s) for s in itertools.product(*lst)]

# ['rux',
#  'ruy',
#  'rvx',
#  'rvy',
#  'rwx',
#   ...
#  'twx',
#  'twy']

Comments

0

Another way? Definitely. Simpler? Maybe not...

I'm guessing it's because you don't necessarily know how many strings you'll have in your list.

What about: sl = ['abc','mno','xyz']

def strCombo(l,s=''):
    if(len(l)==0):
        return s
    elif(len(l)==1):
        return [(s+x) for x in l[0]]
    else:
        return [strCombo(l[1:],(s+x)) for x in l[0]]



final = []
for x in strCombo(sl)[0]:
    final = final + x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.