1

My intention is to rotate the list1 clockwise and print it as list2. See below code for the same. my problem is with third line of the code whenever I am doing this the list1 and list2 point to the same location. To my knowledge if i write list1 = list2 would have done that, however slicing list2 =list1[:] should be producing list2 a copy of list1. Can someone help me on this ?

# Python 3.8
list1 = [[1,2,3],[4,5,6],[7,8,9]]

print (list1[0],list1[1],list1[2],sep='\n')

list2 = list1[:][:]

for i in range(3):

    for j in range(3):

        list2[i][j] = list1[2-j][i]

print ('\n_________\n')

print (list2[0],list2[1],list2[2],sep='\n')

print ('\n_________\n')

print (list1[0],list1[1],list1[2],sep='\n')

Output

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]


[7, 4, 7]

[8, 5, 4]

[9, 4, 7]


[7, 4, 7]

[8, 5, 4]

[9, 4, 7]

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
MohAsin
  • 11
  • 1

1 Answers1

2

Python has the concept of deep copy and shallow copy. The slicing operation generates a shallow copy of list1 in your case.

>>> list1 = [[1,2,3],[4,5,6],[7,8,9]]
>>> print (list1[0],list1[1],list1[2],sep='\n')
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
>>>
>>> list2 = list1[:][:]
>>> list2
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> id(list1)
2123959541504
>>> id(list2)
2123959572032
>>> id(list1[0])
2123958209920
>>> id(list2[0])
2123958209920

Notice how each row points to the same memory location, thus changing row elements in list2 will change list1 also.

You could instead use the copy library of python

>>> from copy import deepcopy
>>> list2 = deepcopy(list1)
>>> id(list2[0])
2123959574016
>>> id(list1[0])
2123958209920
lorem_bacon
  • 165
  • 1
  • 10