Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading