0
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.

1 Answers1

-2

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]
Alex
  • 126
  • 6