There are multiple elements to be deleted in the list, and when I deleted them while looping without thinking about anything, I found an element that matches the conditions but is not deleted.
It was so simple that I scanned it from the top of the list and deleted it, so the combination of index and element was wrong, and the element that was originally deleted remained.
Changed to scan the list from reverse order
lst = [1, 2, 3]
for i in lst:
if i in (1, 2):
lst.remove(i)
print(lst)
#Execution result
[2, 3]
lst = [1, 2, 3]
for I in reversed(lst):
if i in (1, 2):
lst.remove(i)
print(lst)
#Execution result
[3]
If you delete it from the top of the list, the elements will be packed, but the index will remain the same. Therefore, the next deleted element is packed and not processed. Deleting the list from the back prevents the next element to be judged from being packed.
>>> lst = [1, 2, 3]
>>> for i, l in enumerate(lst):
... print("index:%s, value:%s, list:%s" % (i, l, lst))
... if l in (1, 2):
... lst.remove(l)
... print("index:%s, value:%s, list:%s" % (i, l, lst))
...
index:0, value:1, list:[1, 2, 3]
index:0, value:1, list:[2, 3]
index:1, value:3, list:[2, 3]
index:1, value:3, list:[2, 3]
Since the value is 3
when the index is 1
, 2
, which should be removed by the judgment, is not processed. (If index is 1
, value is 2
according to the original list)
Do this in reverse order.
>>> lst = [1, 2, 3]
>>> for i, l in enumerate(reversed(lst)):
... print("index:%s, value:%s, list:%s" % (i, l, lst))
... if l in (1, 2):
... lst.remove(l)
... print("index:%s, value:%s, list:%s" % (i, l, lst))
...
index:0, value:3, list:[1, 2, 3]
index:0, value:3, list:[1, 2, 3]
index:1, value:2, list:[1, 2, 3]
index:1, value:2, list:[1, 3]
index:2, value:1, list:[1, 3]
index:2, value:1, list:[3]
Up to this point, when deleting with ** element **. One thing to be careful of is when deleting with ** index **. When deleting with ** index **, this writing method will result in an error.
>>> lst = [1, 2, 3]
>>> for i, l in enumerate(reversed(lst)):
... print("index:%s, value:%s, list:%s" % (i, l, lst))
... if l in (1, 2):
... del lst[i]
... print("index:%s, value:%s, list:%s" % (i, l, lst))
...
index:0, value:3, list:[1, 2, 3]
index:0, value:3, list:[1, 2, 3]
index:1, value:2, list:[1, 2, 3]
index:1, value:2, list:[1, 3]
index:2, value:1, list:[1, 3]
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: list assignment index out of range
In this case, it can be dealt with by the following.
>>> lst = [1, 2, 3]
>>> for i, l in reversed(list(enumerate(lst))):
... print("index:%s, value:%s, list:%s" % (i, l, lst))
... if l in (1, 2):
... del lst[i]
... print("index:%s, value:%s, list:%s" % (i, l, lst))
...
index:2, value:3, list:[1, 2, 3]
index:2, value:3, list:[1, 2, 3]
index:1, value:2, list:[1, 2, 3]
index:1, value:2, list:[1, 3]
index:0, value:1, list:[1, 3]
index:0, value:1, list:[3]
Recommended Posts