Nico Schlömer Nico Schlömer - 1 year ago 34
Python Question

Iterate over every black square of a "chessboard"

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

"chessboard", i.e.,

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) % 2 == 0

Answer Source

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]