# Python list remove() deletes adjacent duplicate elements, which will omit a solution

2022-01-26 22:54:16

``` problem ：remove( Element name ) When using a loop to delete multiple elements with duplicate names , If two elements should have been deleted  adjacent , The second element will be skipped automatically .
terms of settlement :
①while loop ： Remove elements 1 after , The subscript does not move back
②for loop ： Add auxiliary list
③for loop ： Reverse delete
④while loop ： Will judge whether the element is in the list as a loop condition
```
``````'''
problem ：remove( Element name ) When using a loop to delete multiple elements with duplicate names , If two elements that should have been deleted are adjacent , The second element will be skipped automatically .
terms of settlement :
①while loop ： Remove elements 1 after , The subscript does not move back
②for loop ： Add auxiliary list
③for loop ： Reverse delete
④while loop ： Will judge whether the element is in the list as a loop condition
'''
li=[2," yogurt "," yogurt ",1,1]
# Wrong situation
for i in li:
if i==" yogurt ":
li.remove(" yogurt ")
print(li)
# result ：[2, ' yogurt ', 1, 1]

# terms of settlement
#①while loop ： Remove elements 1 after , The subscript does not move back
i=0
while i<len(li):
if li[i] == " yogurt ":
li.remove(" yogurt ")
else:
i+=1
print(li)
# result ：[2, 1, 1]

# ②for loop ： Add auxiliary list
help1=[]
for i in li:
if i != " yogurt ":
help1.append(i)
print(help1)
# result ：[2, 1, 1]

# ③for loop ： Reverse delete
for i in li[::-1]:
if i == " yogurt ":
li.remove(" yogurt ")
print(li)
# result ：[2, 1, 1]
# reason ： Traversal is from back to front , The deletion is also from the back to the front , Delete the following , Does not affect the subscript of the preceding element

# ④while loop ： Will judge whether the element is in the list as a loop condition
del_ele=" yogurt "
while del_ele in li:
li.remove(" yogurt ")
print(li)
# result ：[2, 1, 1]

``````