First question: Write the results of the final print
A = [1, 2, 3, 4]for x in a: a.remove (x) print (a) print ("=" *) b = [1, 2, 3, 4]for i in B: B.pop () print (b) print ("=" *) c = [1, 2, 3, 4]for I in range (Len (c)): del c[0]print (c)
At first, it should all be []??
Ran a bit on the machine:
[2, 4]
====================
[1, 2]
====================
[ ]
Get the results as above, is not very surprised!!
The first thing to understand is the difference between the three Remove,pop,del
1. Remove the specified element with the remove ("") method, without the time error of the element.
>>> number = [1,3,2,3,4]>>> Number.remove (3) >>> print (number) [1, 2, 3, 4]>>> Number.remove (5) Traceback (most recent): File ' <stdin> ', line 1, in <module>valueerror: List.remove (x): X not in List
2. Use the del[index] function to delete the element with the specified number of indexes
>>> number = [' A ', ' C ', ' d ']>>> del number[1] #删除指定索引数的元素 >>> Print (number) [' A ', ' d ']
3. Popup element with Pop () method, the last element is ejected by default when no index number is in ()
>>> number = [1,2,30,0]>>> Number.pop () #无索引弹出最后一个元素0 >>> number.pop (1) #弹出索引为1的元素2 >> > Print (number) [1, 30]
above is For the usage of the three, it is important to note that Del is a Python statement, not a list method, and cannot be called through list
Look at the changes in the index of the loop for List A
A = [1, 2, 3, 4]for Index, X in Enumerate (a): print ("The index is {}, the value to be removed is {}, the length of the list is {}". Format (index, X, Len (a))) A.remove ( x) print ( "=" *) print (a) results as follows: The index is 0, the value to remove is 1, the length of the list is 4==================== index is 1, the value to remove is 3, the length of the list is 3======== ============[2, 4]
The length of the list is changing, and the index value is changing. This is a point that is easy to overlook because the For loop object is an object that can be iterated.
The difference between Remove,pop,del in Python