grizzasd
grizzasd

Reputation: 383

How to Condense Nested Loops in Python

I have a 2D list containing lists of different words. I have a set of 12 nested for loops. I need to loop through every possible combination of elements in the 2D list and perform a simple calculation on the result.

I originally did this using the itertools.product() function, followed performing the calculation on each resulting list, however the result of the itertools.product() call became too large and I would run out of memory. This means I need the calculation to be performed after every iteration.

My code looks something like this:

for word1 in possible_words[0]:
    for word2 in possible_words[1]:
            for word3 in possible_words[2]:
                    for word4 in possible_words[3]:
                            for word5 in possible_words[4]:
                                    for word6 in possible_words[5]:
                                            for word7 in possible_words[6]:
                                                    for word8 in possible_words[7]:
                                                            for word9 in possible_words[8]:
                                                                    for word10 in possible_words[9]:
                                                                            for word11 in possible_words[10]:
                                                                                    for word12 in possible_words[11]:
                                                                                        result = ' '.join([word1, word2, word3, word4, word5, word6, word7, word8, word9, word10, word11, word12])                                                                                            
                                                                                        if get_address(result) == desired_address:
                                                                                            return result

This code works fine and does what I need. However, I want to know if there is a way I can condense this down in a more pythonic way?

Upvotes: 2

Views: 765

Answers (1)

Netwave
Netwave

Reputation: 42796

Use itertools.product, just iterate through the iterator, don't build a list with it:

from itertools import product

for words in product(*possible_words):
    result = " ".join(words)
    if result == desired_string:
        return result

Upvotes: 4

Related Questions