0

Why is the supplied list getting altered even when I have done all the operations in m list variable sliced from supplied matrix list.

def matrixflip(matrix, d):
    m = matrix[:]
    lenghth = len(m)
    if d == 'h':
        for i in m:
            i.reverse()
        return m

    elif d == 'v':
        for i in range(lenghth//2):
            for j in range(len(m[0])):
                (m[i][j] , m[lenghth-1-i][j]) = (m[lenghth-1-i][j] , m[i][j])
        return m
    else : return m


myl = [[1, 2], [3, 4]]
p = matrixflip(myl,'v')
print(p)
print (myl)

[[3, 4], [1, 2]]

[[3, 4], [1, 2]]

but I need to have an input matrix(myl) unchanged

1 Answers1

1

Slicing doesn't do a deep copy. It only does a shallow copy.

So, when you slice a list of lists, you will get a copy of only your outer list, but that copy will refer to the same inner lists.

So, when you modify that inner list, the modification will be visible from your original outer list, as well as from the copy of that outer list created by the slice.

To perform a deep copy, import copy, and call copy.deepcopy(my_list_name).

fountainhead
  • 3,584
  • 1
  • 8
  • 17