0

I was trying to copy a list to sort the copy but for some reason it sorted the original list as well. Here is the code part. I use the debugger to figure out what happened after the sort function.

p = [7,1,5,3,6,4]
copy = p

now according to debugger, (copy = [7,1,5,3,6,4]) then I do

copy.sort(reverse = True)

But now both copy and p = [7,6,5,4,3,1] I found the solution by copy = p.copy(). But I don't understand why original list also changed.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    `copy = p` *doesn't copy anything, assignment never copies*. You should check out the following for getting a handle on Python's semantics with regards to assignment: https://nedbatchelder.com/text/names.html if you want a copy, you have to explicitly request one. List objects (and many other built-in objects) have a `.copy` method, so `copy = p.copy()` would work, or another common idiom is taking a "full slice", `copy = p[:]`, note, both of these will make shallow copies, but that shouldn't matter in your sorting case – juanpa.arrivillaga Apr 23 '23 at 05:18

1 Answers1

2

If you want a second variable to be a unique copy of another list, you can call its copy method.

For example:

>>> a=[3,2,1]
>>> b=a.copy()
>>> a.sort()
>>> a
[1, 2, 3]
>>> b
[3, 2, 1]

Otherwise if you just do b = a , then b is just a reference to a, both pointing to the same object.


By the way, the idiomatic way to sort a list, when it doesn't have to be in-place, is to use sorted, i.e.

>>> a=[3,2,1]
# this:
>>> b=a.copy()
>>> b.sort()
# ..is equivalent to:
>>> b=sorted(a)

.sort() is useful whenever you want to avoid creating a copy of the list you need sorted, since you will only ever be dealing with the original list once its items are in order.

pflakus
  • 99
  • 6
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38