-3

I want to have a copy of my list, and then sort it, but due of the way that python works, if i sort the copy of the list, it sort also the original list. Here is my code:

def swapBySoting(arr):
    newArr = arr
    newArr.sort()
    swap = 0
    for i in range(len(arr)):
        if arr[i] != newArr[i]:
            swap +=1
    return int(swap / 2)

I only need to know how to store the copy in another reference of memory, to sort only the copy. Thanks

Matteo Possamai
  • 455
  • 1
  • 10
  • 23
  • 1
    the short answer is `newArr` and `arr` still point to the same thing in memory. So when you sort one, you sort both. This is a common stumbling block but there is lots of documentation about it. – SuperStew Sep 17 '20 at 14:21
  • 2
    Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) As mentioned above, `newArr = arr` does not make a copy. You need to explicitly copy the list if you want a copy. – Carcigenicate Sep 17 '20 at 14:22
  • 2
    Assuming you fix the "both array are sorted" error by following Carcigenicate's link, then you function currently counts the number of misplaces items, divided by 2. How are you sure that this number is equal to the minimum number or swaps required to sort the array? – Stef Sep 17 '20 at 14:25
  • Please [edit] the question to have a descriptive title, maybe something like "Why are these two arrays the same?" ["Can someone help me" is not a real question.](https://meta.stackoverflow.com/q/284236/4518341) – wjandrea Sep 17 '20 at 14:28

1 Answers1

2

Assignment just creates a new alias of an object, it doesn't perform a copy. You have two simple solutions:

  1. Shallow copy the first list when assigning to the second:

    newArr = arr[:]  # Or arr.copy()
    
  2. Combine your copy and sort into a single step with the sorted built-in (that creates a new list, sorts it, and returns the new list):

    newArr = sorted(arr)  # No need to call .sort() afterwards
    

Side-note: For comparing elements, looping over indices is relatively slow and unpythonic. Using zip and unpacking to useful names gets the much nicer (and a titch faster):

for old, new in zip(arr, newArr):
    if old != new:
        swap +=1

That said, this algorithm for counting minimum swaps is almost certainly wrong, but that's another question entirely.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271