The following is a sharing of pitfalls that you should pay attention to when deleting elements from a python list. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
Let’s directly give the code whose output is different from expected
In[28]: a = [1,2,3,4,5,6] In[29]: for i in a: ...: a.remove(i) ...: In[30]: a Out[30]: [2, 4, 6]
In the above for loop, assuming we delete the value of index=2, the original index=3 and subsequent values will be filled forward, so the original index=3 variable is skipped in the loop
Similarly, when using the list.pop() function to delete specified elements, the above situation will also occur, such as:
In[33]: a = [1,2,3,4,5,6] In[34]: for index, value in enumerate(a): ...: a.pop(index) ...: In[35]: a Out[35]: [2, 4, 6]
If we want to delete elements in the list in a loop, the simpler methods available are: use a temporary list to save the elements to be deleted, and loop the temporary list in a for loop to delete elements in the old list; or directly Overwrite the original list with the remaining element list
Related recommendations:
Two methods and examples of python list sorting
The above is the detailed content of Pitfalls to pay attention to when deleting elements from python list. For more information, please follow other related articles on the PHP Chinese website!