0

The program gives the desired output but there is a side effect.The argument should not be modified but the function modifies it.

I have already tried making a copy of the argument by taking a full slice of the argument list.

def rotate(m):
    A = m[::]

    for i in range(len(A)):
            for j in range(i + 1, len(A)):
                A[i][j], A[j][i] = A[j][i], A[i][j]

    for i in range(len(A)):
        A[i] = A[i][::-1]

    print(A)

rotate([[1,2,3],[4,5,6],[7,8,9]])

The expected output is:

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

The output is as expected. The code should not modify the argument but it does.

Itay
  • 16,601
  • 2
  • 51
  • 72
jm_111
  • 13
  • 3
  • The lists within `m` aren't being copied, you're modifying *them* directly. – deceze Aug 22 '19 at 06:37
  • tried with `deepcopy`? – FObersteiner Aug 22 '19 at 06:39
  • @jm_111: just check the link to the duplicate, you'll find all the info you need there. – FObersteiner Aug 22 '19 at 06:41
  • deepcopy worked. Is there any other possible way to do it, without importing anything? I would be glad if you could explain what the issue is in the given code. – jm_111 Aug 22 '19 at 06:46
  • You have a list `m` which contains other lists. E.g. `n = [1, 2, 3]; m = [n]`. When you make a copy of `m`, the containing `n` is not copied (shallow copy). There's still only one `[1, 2, 3]` object that's referenced multiple times now. – deceze Aug 22 '19 at 07:00
  • check out [this resource](https://nedbatchelder.com/text/names.html). Since you have lists in a list, you need `deepcopy` (shallow copy is not enough). That's also noted in the duplicate [here](https://stackoverflow.com/a/2612815/10197418). – FObersteiner Aug 22 '19 at 07:03

0 Answers0