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?
For loops are faster than list comprehensions to run functions.
As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.
Conclusions. List comprehensions are often not only more readable but also faster than using "for loops." They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.
Are you asking about this?
[ (i,j) for i in range(1,3) for j in range(1,5) ]
Cartesian product is in the itertools module (in 2.6).
>>> import itertools
>>> list(itertools.product(range(1, 3), range(1, 5)))
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With