0
nums = [100,20,30,90]
temp_arr = nums
answer = 0
print(nums, temp_arr)
def insertionSort(arr):
    for i in range(1, len(arr)):
        key = arr[i] 
        j = i-1
        while j >= 0 and key < arr[j] :
                arr[j + 1] = arr[j]
                j -= 1
        arr[j + 1] = key
 
insertionSort(temp_arr)
print(nums, temp_arr)

Idk why the array nums is getting sorted when im only trying to sort the temp_arr

  • Variables storing non-primitive values (such as lists) actually store references to them. By `temp_arr = nums` you make `temp_arr` and `nums` refer to the same list. – daylily Jul 13 '21 at 19:16

2 Answers2

0

nums and temp_arr are the same object in memory. When you write temp_arr = nums, you are introducing a new name (temp_arr) that references that same object as nums

Try:

nums is temp_arr

This should return the result True, since nums is the same object as temp_arr.

To make a new object, you can use:

temp_arr = nums.copy()

This will actually make a copy of the object and make temp_arr reference this new copy. Then try the same test using is, this should now return False

Pippet39
  • 127
  • 4
0

The reason for this is because your assignment

temp_arr = nums

is done by reference and not by value. So to say it simple any changes to "temp_arr" also affects "nums".

You may find a solution for this here: List changes unexpectedly after assignment. Why is this and how can I prevent it?

Warzulus
  • 46
  • 5