Replace Elements with Zeros in Python

Today, we will see how to replace elements with zeros in Python. We will write two programs for that, in the first one, we will see how to replace elements with zeros in a matrix created using lists in Python, and in the second one, we will use NumPy.

1. Replace Elements with Zeros in a matrix of List in Python

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

for i in range(len(matrix)):
    for j in range(len(matrix)):
        matrix[i][j] = 0
        
print(matrix)

Output:

Replace Elements with Zeros in a matrix of List in Python | Assignment Expert

2. Replace Elements with Zeros in a matrix of List in Python

import numpy as np

matrix = np.array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

for i in range(len(matrix)):
    for j in range(len(matrix)):
        matrix[i][j] = 0
        
print(matrix)

Output:

Replace Elements with Zeros in a matrix of List in Python | Assignment Expert

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you