Martin
Martin

Reputation: 3

Reducing code for iterating over the same list with nested for loops but with different variables

Is there any in build python iterating tool that reduces 3 row of for loops into one row? Here are the nested for loops that I want to reduce.

some_list = ["AB", "CD", "EF", "GH"]

for word_1 in some_list:
    for word_2 in some_list:
        for word_3 in some_list:
            print(word_1, word_2, word_3) #Outputs all different combinations

I have tried the following but with no success:

some_list = ["AB", "CD", "EF", "GH"]

for word_1 ,word_2, word_3 in zip(some_list, some_list, some_list):
    print(word_1 , word_2, word_3) #Outputs parallel elements, which is not what I want.

Upvotes: 0

Views: 25

Answers (1)

Alex P
Alex P

Reputation: 1155

Yes there is, it's product from itertools.

from itertools import product

some_list = ["AB", "CD", "EF", "GH"]

for word_1 ,word_2, word_3 in product(some_list, repeat=3):
    print(word_1 , word_2, word_3)

You can also use tuple unpacking to make it even more concise, like this

some_list = ["AB", "CD", "EF", "GH"]

for words in product(some_list, repeat=3):
    print(*words)

Output (in both cases):

AB AB AB
AB AB CD
AB AB EF
AB AB GH
AB CD AB
AB CD CD
AB CD EF
AB CD GH
AB EF AB
AB EF CD
...

Upvotes: 1

Related Questions