w3resource

NumPy: Create a 8x8 matrix and fill it with a checkerboard pattern


8x8 Checkerboard Pattern

Write a NumPy program to create an 8x8 matrix and fill it with a checkerboard pattern.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x3 NumPy array filled with ones
x = np.ones((3, 3))

# Printing a message indicating the checkerboard pattern
print("Checkerboard pattern:")

# Creating an 8x8 NumPy array filled with zeros and setting alternate elements to 1 to create a checkerboard pattern
x = np.zeros((8, 8), dtype=int)
x[1::2, ::2] = 1  # Setting alternate rows starting from the second row with alternate columns to 1
x[::2, 1::2] = 1  # Setting alternate rows starting from the first row with alternate columns to 1

# Printing the resulting checkerboard pattern array
print(x) 

Sample Output:

Checkerboard pattern:                                                   
[[0 1 0 1 0 1 0 1]                                                      
 [1 0 1 0 1 0 1 0]                                                      
 [0 1 0 1 0 1 0 1]                                                      
 [1 0 1 0 1 0 1 0]                                                      
 [0 1 0 1 0 1 0 1]                                                      
 [1 0 1 0 1 0 1 0]                                                      
 [0 1 0 1 0 1 0 1]                                                      
 [1 0 1 0 1 0 1 0]]

Explanation:

In the above code –

x = np.ones((3,3)): Creates a 3x3 NumPy array filled with ones. However, this line is not relevant to the final output and can be ignored.

x = np.zeros((8,8),dtype=int): Creates an 8x8 NumPy array filled with zeros, with an integer data type.

x[1::2,::2] = 1: Assigns the value 1 to every other element in every other row, starting from the second row (index 1).

x[::2,1::2] = 1: Assigns the value 1 to every other element in every other column, starting from the second column (index 1).

print(x): Prints the 8x8 NumPy array.


For more Practice: Solve these Related Problems:

  • Create an 8x8 checkerboard pattern using modulo operations on the indices.
  • Generate a checkerboard pattern with custom alternating values and verify the pattern programmatically.
  • Implement the checkerboard without using any loops by leveraging NumPy’s indexing features.
  • Extend the checkerboard pattern function to accept any even dimensions and custom cell values.

Go to:


PREV : Add Border to Array (0s)
NEXT : List/Tuple to Arrays


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.