Why this python code does not work

  • 0
    def moveZeroes(self, nums):
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        size = len(nums)
        nums = [x for x in nums if x != 0]

    This code has problem when there are no zeros in the list. However, "nums = [x for x in nums if x != 0]" seems return the same list. It works in the python editor but not for the OJ.

  • 0

    Just test as following:

    s = Solution()  
    nums = [1, 0, 3, 0, 13, 0, 0]  
    print nums  

    So nums didn't change.
    See this: How do I pass a variable by reference?

    Your code is as new_nums = [x for x in nums if x != 0],
    and the old nums didn't change.

  • 0

    Thanks for the nice link and help!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.