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?
Are you asking about this?
This seems to do what you describe:
[[a,b] for a in range(1,3) for b in range(1,5)]
UPDATE: Drat! Should have reloaded the page to see S.Lott's answer before posting. Hmmm... what to do for a little value-add? Perhaps a short testimony to the usefulness of interactive mode with Python.
I come most recently from a background with Perl so with issues like this I find it very helpful to type "python" at the command line and drop into interactive mode and just a)start trying things, and b)refine the niceties by hitting up-arrow and adjusting my previous attempt until I get what I want. Any time I'm hazy on some keyword, help is at hand. Just type: help("some_keyword"), read the brief summary, then hit "Q" and I'm back on line in direct conversation with the python interpreter.
Recommended if you are a beginner and not using it.
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:
generates all pairs
(i,j)
where0>=i>j>10
.Cartesian product is in the itertools module (in 2.6).