Pit stepping record of remove function in python

  • 2021-09-05 00:29:33
  • OfStack

Summary:

During the use of python, it is inevitable to encounter the requirement of removing objects from the list. You can use the remove function at this point.

The official document interprets the remove () function in python as: Remove first occurrence of value to remove the first matching element in the list equal to the specified value.

Grammar

list.remove()

Parameter

obj Parameter: The index of the object removed from the list

Return value

No value will be returned after deletion

Common usage:

a = [1, 2, 3, 4], a. remove (1), then a is [2, 3, 4]; For a = [1, 1, 1, 2], the result is also [1, 1, 2], which is the most basic usage.

But for this one:


a = [1,2,3,4]
for i in a:
  a.remove(i)

#  Results 
a = [2,4]

Or say


a = [1,1,1,1,1,2]
for i in a:
  a.remove(1)

 
# Results 
a = [1,1,2]

Is it different from what you think? The main reasons are as follows (^ indicates where the current iterator is in the list):

a = [ 1 , 2 , 3 , 4]

Suppose at this time ^

By default, you only want the first element, then execute a. remove (1), then the subscript moves backward, and the list moves forward because the element is deleted, as follows:

a = [ 2 , 3 , 4]

At this time ^

At this point, a. remove (3) is executed, repeating the above move

a = [ 2 , 4]

At this time ^

Because the boundary of the list has been reached, the traversal ends and returns ` a = [2, 4] `.

Solution:


# 1 The following is the solution 1
d = dict(zip(range(len(a)), a))
[v for k, v in d.items() if v != value]

Summary:

The remove operation on the python list involves moving the subscript of the list and moving the elements in the list, which involves some knowledge about arrays. Its core problem is what I said earlier.


Related articles: