0

the purpose of the code is to merge nums2 into nums1 as one sorted array. the first approach doesn't work as expected, the second one works fine, any explanation?

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        nums1 = sorted(nums1[:m]+nums2[:n])

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        nums1[m:]=nums2
        nums1.sort() 
Flupper
  • 310
  • 2
  • 15

2 Answers2

2

In the first example, sorted creates a new list that only lives for the duration of the function body. The nums1 label that you give to that new list effectively shadows the input parameter named nums1.

In the second example, you modify nums1 in-place, which affects the calling object. You never create any new variables, you are only working with memory that is external to the function.

Generally the first solution is preferred (assuming you modify it to return the modified list) because it is very clear at the call site that the function will modify the list that was passed in. The second solution should only be used under rare circumstances.

0x5453
  • 12,753
  • 1
  • 32
  • 61
1

sort() change the list in-place, while sorted() builds a new sorted list

eg:

l = [3, 4, 1]
a = sorted(l)
print(a, l)
out: [1, 3, 4] [3, 4, 1] # l does not change

b = l.sort()
print(b, l)
out: None [1, 3, 4] # l changes and b is None because list().sort returns None

The official python docs are probably the best docs you can find to learn python, check this: Sorting HOW TO

also: What is the difference between `sorted(list)` vs `list.sort()`?

Hoxha Alban
  • 1,042
  • 1
  • 8
  • 12
  • Thank you @Hoxha Alban, I already knew the difference between sorted() and sort() what I missed is the shadowing definition. appreciated your efforts bro – Flupper Jun 05 '20 at 21:49