As a new python programmer, I have two questions about list and really appreciate your advice:
Question 1:
For the following code:
nums1 = [1,2,3,8,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1, m, nums2, n):
nums1[:] = sorted(nums1[:m]+nums2)
merge(nums1, m, nums2, n)
nums1
What it does is: pass list nums1 and list nums2 into merge function, and merge them into list nums1 with the first m items in nums1 and n items in nums2, and sort list nums1. So the results are: [1, 2, 2, 3, 5, 6] So my question is: since list nums1 was defined outside the scope of function merge, how come it has the ability to update nums1? And in the following example:
x = 10
def reassign(x):
x = 2
reassign(x)
x
Variable x was defined outside of function reassign, and the reassign function was not able to update x defined outside of reassign, which is why x returns 10.
Question 2:
In the above code I provided, if I write it like the following:
Note: I just modified nums1[:] into nums1 when assigning sorted(nums1[:m]+nums2)
nums1 = [1,2,3,8,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
def merge(nums1, m, nums2, n):
nums1 = sorted(nums1[:m]+nums2)
merge(nums1, m, nums2, n)
nums1
nums1 returns [1,2,3,8,0,0,0], so my question is: after adding [:] after nums1, how come the function has the ability to nums1? What does [:] in that example?