0

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?

1
  • 2
    arr1 = arr doesn't copy the list. It just makes a new reference to the same object in memory, so changes to one reflect on the other. Use arr1 = arr[:] to copy the list using slice notation. Then, when you call arr1.sort(), it will only mutate arr1 in-place, leaving arr unchanged. Commented Oct 22, 2019 at 16:59

1 Answer 1

1

sort() is in-place function in python and lists are pass by reference. So, if one array is getting sorted in-place it will change another, too.

If you want to prevent that, you can use:

arr = arr1[:]

or

import copy
arr = copy.deepcopy(arr1)
Sign up to request clarification or add additional context in comments.

1 Comment

... or arr = arr1.copy(), which is the One Obvious Way to do a list copy ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.