I'm submitting the answer in leetcode(27).I need to get back the correct list and length. When I plan to do this.
Input: [3,2,2,3] 3
class Solution:
def removeElement(self, nums, val):
if not nums:
return 0
nums = [i for i in nums if val != i]
return len(nums)
Output: [3,2]
Expected: [2,2]
Clearly my answer is wrong. But when I write it this way, the solution is correct.
class Solution:
def removeElement(self, nums, val):
if not nums:
return 0
nums[:] = [i for i in nums if val != i]
return len(nums)
Output: [2,2]
Expected: [2,2]
I don't understand the difference between these two ways. Why do I get two different lists?
答案 0 :(得分:0)
nums[:] change the original nums inplace.