Home  >  Article  >  Backend Development  >  Pitfalls to pay attention to when deleting elements from python list

Pitfalls to pay attention to when deleting elements from python list

不言
不言Original
2018-04-18 11:23:472006browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn