Ammar Salahi
Ammar Salahi

Reputation: 33

Swap two indices in Python 2D array

I wrote a function as follows:

def change_value(array):
    for i in range(len(array)):
        for j in range(len(array[i])):
            if array[i][j]==0:
                array[i][j],array[0][0]= array[0][0],array[i][j]
            print(array[i][j],end=' ')
        print()
array=[[1,2,3],[4,0,6],[7,8,5]]
change_value(array)

This function exchanges the values ​​of the two desired indices after receiving the array. But the output was as follows:

1 2 3
4 1 6
7 8 5

What is the solution to this problem?

Upvotes: 1

Views: 735

Answers (2)

Timo
Timo

Reputation: 493

While AKX solution is correct, note that the pythonic way to solve the problem would be

import numpy as np
array = np.array([[1, 2, 3], [4, 0, 6], [7, 8, 5]])
mask = (array == 0)

array[mask], array[0, 0] = array[0, 0], array[mask]
print(array)

Upvotes: 0

AKX
AKX

Reputation: 169032

The problem is you're printing each value as you go - with the zero value in position (1, 1) you have already printed out the 0th row that would have had a value swapped in a future iteration.

Decouple the swapping code and the printing code:

def change_value(array):
    for i in range(len(array)):
        for j in range(len(array[i])):
            if array[i][j] == 0:
                array[i][j], array[0][0] = array[0][0], array[i][j]


def print_array(array):
    for row in array:
        for cell in row:
            print(cell, end=" ")
        print()


array = [[1, 2, 3], [4, 0, 6], [7, 8, 5]]
print_array(array)
print("===")
change_value(array)
print_array(array)

Upvotes: 1

Related Questions