Welcome, guest | Sign In | My Account | Store | Cart

With list comprehension, you can easily loop through all combinations of 2 or 3 lists. But what about more, like 4,6, 20? This recipe show a way to do this, without use of recursion.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
a = [[1,2],[3,4,5],[6],[7,8,9,10]]

r=[[]]
for x in a:
    t = []
        for y in x:
            for i in r:
                t.append(i+[y])
    r = t

print r

-------------------------------
[[1, 3, 6, 7], [2, 3, 6, 7], [1, 4, 6, 7], [2, 4, 6, 7], [1, 5, 6, 7], [2, 5, 6, 7], [1, 3
, 6, 8], [2, 3, 6, 8], [1, 4, 6, 8], [2, 4, 6, 8], [1, 5, 6, 8], [2, 5, 6, 8], [1, 3, 6, 9
], [2, 3, 6, 9], [1, 4, 6, 9], [2, 4, 6, 9], [1, 5, 6, 9], [2, 5, 6, 9], [1, 3, 6, 10], [2
, 3, 6, 10], [1, 4, 6, 10], [2, 4, 6, 10], [1, 5, 6, 10], [2, 5, 6, 10]]

At each outermost iteration, the number of result list r multiply by the number of items of current item(list). At each inner iteration, the list item i (itself is a list) is replace by a new list.

3 comments

Rodney Drenth 17 years ago  # | flag

Improve by using list comprehension. The lines within the outer loop could be replaced with a list comprehenstion like:

r = [ i + [y] for y in x for i in r ]
Babu A 14 years, 9 months ago  # | flag

Thank you very much, I am looking for this function and helped in my work

Aaron Newton 11 years, 10 months ago  # | flag

Good work. But I'm going to play devils advocate and ask why you didn't just use itertools.product? http://docs.python.org/library/itertools.html?highlight=itertools#itertools.product

Created by Wensheng Wang on Mon, 19 Jun 2006 (PSF)
Python recipes (4591)
Wensheng Wang's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks