pythonlist

Output is different than Stdout in Python


I'm new to programming and I'm trying Leetcode. The question asks to store the answer inside nums1. When I print nums1, the stdout shows the correct answer but the output is not the same?

enter image description here

class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """

        for x in range(n):
            nums1.remove(0)

        nums1 = nums1 + nums2
        nums1.sort()
        print(nums1)

This is what it shows:

enter image description here


Solution

  • LeetCode only remembers the memory reference of the initial nums1 list, so if you update it using nums1 = nums1 + nums2, the original array won't be updated and instead a new reference is created. Weird, I know.

    The solution to this is to use nums1.extend(nums2) which modifies the list in place instead of nums1 = nums1 + nums2.


    To clarify, your code is not exactly the best solution here. I have only solved your problem of not being able to submit your answer. It must be admitted that I am anything but an expert in these algorithms, but @SIGHUP seems to be rather well-versed in this topic, so you could enquire him and/or read his answer, which probably displays right below this answer.