pythonarraysmatrixpointer-aliasing

Is there aliasing in a 2-D array in Python?


I know that list aliasing is an issue in Python, but I can't figure out a way around it.

def zeros(A):
    new_mat = A
    for i in range(len(A)):
        for j in range(len(A[i])):
            if A[i][j]==0:
                for b in range(len(A)):
                    new_mat[b][j] = 0
            else:
                new_mat[i][j] = A[i][j]
    return A

Even though I don't change the values of A at all, when I return A, it is still modified:

>>> Matrix = [[1,2,3],[5,0,78],[7,3,45]]
>>> zeros(Matrix)
[[1, 0, 3], [5, 0, 78], [7, 0, 45]]

Is this list aliasing? If so, how do you modify elements of a 2D array without aliasing occurring? Thanks so muhc <3.


Solution

  • new_mat = A does not create a new matrix. You have merely given a new name to the object you also knew as A. If it's a list of lists of numbers, you might want to use copy.deepcopy to create a full copy, and if it's a numpy array you can use the copy method.