What is the difference between [:] and [] in python?

时间:2018-02-01 18:06:41

标签: python

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?

1 个答案:

答案 0 :(得分:0)

nums[:] change the original nums inplace.

https://docs.python.org/3/tutorial/introduction.html#lists