How to make a checkerboard in numpy?

numpy, python

Solution

def checkerboard(shape):
    return np.indices(shape).sum(axis=0) % 2

Most compact, probably the fastest, and also the only solution posted that generalizes to n-dimensions.

Problem

I'm using numpy to initialize a pixel array to a gray checkerboard (the classic representation for "no pixels", or transparent). It seems like there ought to be a whizzy way to do it with numpy's amazing array assignment/slicing/dicing operations, but this is the best I've come up with: ``` w, h = 600, 800 sq = 15 # width of each checker-square pix = numpy.zeros((w, h, 3), dtype=numpy.uint8) # Make a checkerboard row = [[(0x99,0x99,0x99),(0xAA,0xAA,0xAA)][(i//sq)%2] for i in range(w)] pix[[i for i in range(h) if (i//sq)%2 == 0]] = row row = [[(0xAA,0xAA,0xAA),(0x99,0x99,0x99)][(i//sq)%2] for i in range(w)] pix[[i for i in range(h) if (i//sq)%2 == 1]] = row ``` It works, but I was hoping for something simpler.

Original source