Python program to print a checkboard pattern of n*n using numpy.



The checkboard pattern is the square grid composed of alternating 0s and 1s, arranged in a way that no two adjacent cells have the same value. It looks like the chessboard, where black and white squares alternate in every row and column.

This kind of pattern is not only seen in chess or checkers, but also in image processing, graphics, and visualization, etc. In this article, we are going to learn how to print a checkboard pattern of n*n using numpy.

Using Python numpy.indices() Method

The numpy.indices() method is used to return the grid of indices with the given shape. It creates the coordinate matrices from coordinate vectors.

Syntax

Following is the syntax of Python numpy.indices() method -

numpy.indices(dimensions, dtype=int)

Example 1

Let's look at the following example, where we are going to print a checkboard of 2*2 pattern.

import numpy as np
def demo(n):
    result = (np.indices((n, n)).sum(axis=0)) % 2
    print(result)
demo(2)

The output of the above program is as follows -

[[0 1]
 [1 0]]

Example 2

In the following example, we are going to use the 4*4 to print a checkboard pattern.

import numpy as np
def demo(n):
    result = (np.indices((n, n)).sum(axis=0)) % 2
    print(result)
demo(4)

The following is the output of the above program -

[[0 1 0 1]
 [1 0 1 0]
 [0 1 0 1]
 [1 0 1 0]]
Updated on: 2025-06-17T17:37:02+05:30

574 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements