Do you know the answer to the following question ?
Let's now define a list a, The contents are as follows :
a = [1,2,3,4,5,6,7,8,9,10]
Yes python We all know the basics , Actions on lists ,python Some built-in functions are provided , such as append,count,extend,pop,insert,remove,reverse Equifunction , Now let's take a look at a piece of code , What do you think is the output after implementation ?
a = [1,2,3,4,5,6,7,8,9,10] for i in a: a.remove(i) print(a)
remove Is the method to remove list elements , So what is the final result of this script ?
Is your answer correct ?
After thinking for a moment , Do you think , The final output is an empty list ?
Obviously , The final output is certainly not an empty list , The final output is :
[2, 4, 6, 8, 10]
yes , You're not wrong , The final output is :[2, 4, 6, 8, 10].
So why is the output empty list ? Because it's in use for i in a When you do this , After not traversing once , delete a After an element in the list ,a The value of the list has changed .
The code runs as follows :
First cycle , Delete the subscript as 0 After the element of , here , list a Change into [2, 3, 4, 5, 6, 7, 8, 9, 10]
Second cycle , Delete the following table as 1 Elements of , The list is now listed a Elements are excluded from the 3, list a Change into [2, 4, 5, 6, 7, 8, 9, 10],
and so on , Finally, the output of the code is :[2, 4, 6, 8, 10]
How to solve these problems ?
1, List a conduct copy After one copy, it is deleted by loop traversal
for i in a.copy(): a.remove(i) print(a)
perhaps
for i in a[:]: a.remove(i) print(a)
2, Reverse the list before traversing and deleting
for i in a[::-1]: a.remove(i) print(a)
Except for traversing the list , When traversing other types of data, we should also pay attention to avoid mining this kind of pit , That's all for today's sharing , If you think it's helpful for you , You can like it .
Technology
Daily Recommendation