Recommand · November 24, 2021 0

Python array sorting with unexpected result

This question already has answers here:

List changes unexpectedly after assignment. Why is this and how can I prevent it?

(22 answers)

Closed 32 mins ago.

def sorted():
    print(numList)
    sortedList=numList
    sortedList.sort()
    print(numList)
    print(sortedList)

Result:
[4,1,9,16,25]
[1,4,9,16,25]
[1,4,9,16,25]

Actually, I just sort the "sortedList" only, but result shows it sorted numList too. may I know the reason and solution.

You need to make a copy of the list, otherwise it is a pointer to the list and will act on both things.

https://www.programiz.com/python-programming/methods/list/copy

Here’s how copy works. You’ll want to copy your numList into sortedList and then sort it.

Example:

lst = [0, 1, 2, 3]
lst2 = lst
lst2[0] = 4

lst
>>> [4, 1, 2, 3]

Versus

lst = [0, 1, 2, 3]
lst2 = lst.copy()
lst2[0] = 4

lst
>>> [0, 1, 2, 3]