Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 735
Federico A. Ramponi Avatar asked Dec 01 '08 02:12

Federico A. Ramponi


People also ask

What is faster than list comprehension Python?

For loops are faster than list comprehensions to run functions.

Can you do nested list comprehension?

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.

Are list comprehensions more efficient?

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.


2 Answers

Are you asking about this?

[ (i,j) for i in range(1,3) for j in range(1,5) ]
like image 88
S.Lott Avatar answered Sep 27 '22 21:09

S.Lott


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)]
like image 31
A. Coady Avatar answered Sep 27 '22 21:09

A. Coady