In python, what is the difference between the array nums[:] and nums?

 

There is a problem in leetcode. The topic is:

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you have to use only O(1) extra space and modify the input array in-place.

The order of elements can be changed. You don't need to consider elements in the array beyond the new length.

error code:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        for i in nums:
            print('----', i)
            if i == val:
                nums.remove(val)
                print(len(nums),nums)
        print(nums)
        return len(nums)

Correct code:

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        for i in nums[:]:
            print('----', i)
            if i == val:
                nums.remove(val)
                print(len(nums),nums)
        print(nums)
        return len(nums)

As can be seen from the above, there is a difference between them [:]

But executing it alone:

    for i in nums[:]:
        print('i',i)
    for ii in nums:
        print('ii',ii)

The output results are the same, why?

In Python, nums a list object. nums[:] Indicates that the slice operation is performed on this list, and the result of the slice operation is to return a new list object, which contains all the elements in the original list.

Although  nums and  nums[:] look similar, there is one important difference between them. When you  nums assign to a variable, that variable is really just a reference to the original list object, so any changes to that variable will be reflected on the original list object. For example:

nums = [1, 2, 3]
new_nums = nums

new_nums[0] = 0

print(nums)  # 输出 [0, 2, 3]

However, if you  nums[:] create a new list object with , any changes to the new list object will not affect the original list object. For example:

nums = [1, 2, 3]
new_nums = nums[:]

new_nums[0] = 0

print(nums)  # 输出 [1, 2, 3]

In this example, we  nums[:] created a new list object  with new_numsand assigned it to a variable  new_nums. Then we modified  new_nums the first element in , but the original list  nums was not modified.

So the difference between nums and  nums[:] is that the former is a reference to the original list object, while the latter is a new, independent list object.

This can explain the solution to the leetcode problem listed above. In fact, the slice is to generate a new copy. instead of quoting.

Guess you like

Origin blog.csdn.net/wywinstonwy/article/details/131476848