Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I replace elements in two-dimensional array in python?

My task is to replace all the elements whose both indexes are odd with 1, and all the elements whose both indexes are even with -1.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can replace elements by using a double index like: array[y][x] if array is list of lists.

This is a example:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
length = len(array)
for y in range(length):
    for x in range(length):
        if y % 2 and x % 2:
            array[y][x] = 1
        elif y % 2 == 0 and x % 2 == 0:
            array[y][x] = 0
print(array)

This will output: [[0, 2, 0], [4, 1, 6], [0, 8, 0]]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading