Printing Checkerboard Pattern of nxn Using NumPy:

We can perform this using nested for loops and some if conditions. But by using the numpy library in python for data science, we will be able to import a 2-D matrix, and we can get the checkerboard pattern using slicing.

In order to print the pattern we will use the following function:

When this function is there, a 2-D matrix is initialized with 0’s at all indices.

  • x[1::2, ::2] = 1 : It shows slicing from first index row till 1+2+2…and then filling all columns with 1 from 0th to 0+2+2… and so on.
  • x[::2, 1::2] = 1: It will slice from 0th row till 0+2+2… and then fill all the columns with 1 starting with 1 till 1+2+2…

Functions of np.zeroes((n,n), dtype=int): As we have already discussed in previous sections, the elements of an array are unknown, but the size of that array is known. NumPy provides many functions for creation of arrays with initial placeholder content. These will minimize the necessity of growing arrays which is an expensive operation. When we use the dtype parameter, it initializes all values with int data-type.

Example: np.zeros,, etc.

Printing Checkerboard Pattern NxN Using NumPy Python for Data Science

So, to learn more about it in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.