0

I am trying to set a list = to another list and then sort the new list using .sort(). However, when I print them out to make sure they stored properly, both lists got sorted when I only set the new list to be. Why is this happening? The first print statement is printing the correct unsorted list, the third statement is correctly printing the new sorted list, but the fourth print statement is supposed to be printing the unsorted list but is printing a sorted list.

def twoSum(self, nums: List[int], target: int)->List[int]:

        print("original list", nums)
        sortedList = nums
        sortedList.sort()
        subset = []
        answer = []
        middle = math.floor((len(nums)/2))
        print("middle is ", middle)
        print("sorted list", sortedList)
        print("unsorted list", nums)
Orangutan
  • 15
  • 5
  • after you do `sortedList = nums` you have two names for the same list, so it doesn't matter which you sort. since there's still only one list, it's sorted. Make a copy instead, or use `sorted()` to make a copy and sort at the same time. – kindall Feb 02 '22 at 19:14
  • That was the issue, thank you for your help – Orangutan Feb 02 '22 at 19:16

3 Answers3

1

When you assign sortedList = nums you are merely copying a reference to nums. Thus if you sort nums, sortedList will refer to that same sorted list. If you don't want that to happen, take a copy - e.g., sortedList = nums.copy()

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

You can also use the builtin sorted() function which returns a new, sorted list.

list1 = [3, 2, 1]
list2 = sorted(list1)
Cargo23
  • 3,064
  • 16
  • 25
0

That is because sortedList = nums means both lists point to the same memory location, this is called assignment by reference, if you want to copy the values only you can do as this thread suggests:

sortedList = nums[:]
Hasan Aga
  • 718
  • 8
  • 27