Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an unknown number of nested loops in python

Tags:

I have a variable number of user-defined lists, each containing words. For example, there may be three lists like the following:

list1 = ["THE", "A"]
list2 = ["ELEPHANT", "APPLE", "CAR"]
list3 = ["WALKED", "DROVE", "SAT"]

What I want is to iterate over every combination in each list, checking each against a dictionary of known words, to see which word-groupings are most like the dictionary. That means the iterations would be like:

[
    "THE ELEPHANT WALKED",
    "THE APPLE WALKED",
    "THE CAR WALKED",
    "THE ELEPHANT DROVE",
    "THE APPLE DROVE",
    "THE CAR DROVE",
    # ...
    "A CAR SAT",
]

The problem is that there can be any number of lists, and each list can contain a variable amount of items. I know that recursion could be used for this, but I need a solution without recursion. The problem I keep having is the fact that there can be a variable amount of lists, otherwise I would just write:

for a in list1:
    for b in list2:
        for c in list3:
            ...

But I won't know where to stop...

like image 272
random Avatar asked Nov 18 '12 18:11

random


People also ask

How do you count nested loops in Python?

To count statements in nested loops, one just separates the counts for the iterations of the outer loop, then adds them: count (nested loop) = count (1st iteration of the outer loop) + count (2nd iteration of the outer loop) + … + count (last iteration of the outer loop)

Is there a limit to nested for loops Python?

While there's Python has no technical limit to understanding complex a nested for loops, there is a human limit. If you have a complex piece of code with many for loops, or complex functions and conditions, using a nested for loop may actually make your code more difficult to understand.

How do you avoid multiple nested loops?

Avoid nested loops with itertools. You can use itertools. product() to get all combinations of multiple lists in one loop and get the same result as nested loops. Since it is a single loop, you can simply break under the desired conditions. Adding the argument of itertools.


1 Answers

itertools.product does exactly what you want:

from itertools import product

lists = [
    ['THE', 'A'],
    ['ELEPHANT', 'APPLE', 'CAR'],
    ['WALKED', 'DROVE', 'SAT']
]

for items in product(*lists):
    print(items)
like image 113
Eric Avatar answered Sep 20 '22 05:09

Eric