20

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...

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
random
  • 255
  • 3
  • 12

2 Answers2

30

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)
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 3
    Given he doesn't know the number of lists, ``product(*lists)`` might be more apt. – Gareth Latty Nov 18 '12 at 18:12
  • 1
    @Lattyware: Was doing that while you commented – Eric Nov 18 '12 at 18:14
  • I am curious as to how `product` is implemented. The only way I could think of to solve the problem was to use recursion. Does `product` use recursion itself? – John Red Feb 15 '16 at 02:36
  • This method only goes down one layer. Is there a way to go down an unknown level of embedded lists. So something like [[[[1,2,3],[4,5,6]],['Test','All']]]? – rdt0086 May 11 '21 at 13:47
  • @rdt0086: Your comment isn't enough for me to understand your question - I recommend asking it as a new question rather than commenting on this answer, and showing precisely what behavior you want. – Eric May 11 '21 at 17:16
1

Using python 3.2

from itertools import product

[" ".join(i) for i in product(list1,list2,list3)]
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
raton
  • 418
  • 5
  • 14