Look at the following code:
arr = [5, 4, 3, 2, 1]
arr1 = arr
arr1.sort()
print(arr, arr1)
The expected output is:
[5, 4, 3, 2, 1] [1, 2, 3, 4, 5]
As, arr1 is getting sorted and not arr.
Although, the output is:
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
How come both lists are getting sorted?
arr1 = arrdoesn't copy the list. It just makes a new reference to the same object in memory, so changes to one reflect on the other. Usearr1 = arr[:]to copy the list using slice notation. Then, when you callarr1.sort(), it will only mutatearr1in-place, leavingarrunchanged.