Nico Schlömer - 11 months ago 28

Python Question

I'd like to iterate over every other element of a

`m`

`n`

`l = []`

for i in range(m):

for j in range(n):

if (i+j) % 2 == 0:

l.append(something(i, j))

I'm using an explicit loop here, but for speed would rather use a list comprehension.

Any hints?

For bonus points, the solution also works for

`i`

`j`

`k`

`(i+j+k) % 2 == 0`

Answer

Well, list comprehension is just like your nested `for`

loop, except that this is done *within* the list brackets:

```
my_list = [something(i, j) for i in range(m) for j in range(n) if (i + j) % 2 == 0]
```

More generally, for `n`

nested loops, you can use `itertools.product`

, like this:

```
from itertools import product
my_list = [something(*p) for p in product(range(n), repeat=n) if sum(p) % 2 == 0]
```

Source (Stackoverflow)