Alex Rivera | Logout

In Python, is there a concise way to use a list comprehension with multiple iterators?

Asked 2008-12-01T02:44:03.420
12

Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code:

[(i,j) | i <- [1,2], j <- [1..4]]

which yields

[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]

Can I obtain a similar behavior in Python in a concise way?

Edit
Report

1 Answer

5

Fun fact about the nested comprehension: it mimics nested "for" loops, so the inner ones can use values from outer ones. This isn't useful in the cartesian product case, but good to know. For example:

[ (i,j) for i in range(10) for j in range(i) ] 

generates all pairs (i,j) where 0>=i>j>10.

answered 2008-12-01T09:12:21.310

Your Answer