-1

enter image description here

>>> n = 0
>>> a_list = ['a','p','l','e']
>>> a_list.insert(1,'a')
>>> a_list.insert(3,'p')
>>> for a in a_list: # I want to del all 'a'
...     if(a == 'a'):
...             del a_list[n]
...     n = n + 1
...     print(a)
...
a
p
p
l
e

Here I want to del all 'a' s after inserting a and p. but the result is not want I expected. I suspect its interpreter have specific order of del and insert. The it might not del all 'a'

  • Also [How to remove items from a list while iterating?](https://stackoverflow.com/q/1207406) – SuperStormer Jan 09 '22 at 02:20
  • If you really want to remove from a list in-place while iterating over it, it is useful to iterate backwards. But doing loops in Python is often slower than otherwise-suboptimal code that manages to take advantage of C implementations. – o11c Jan 09 '22 at 02:35

1 Answers1

1

You're removing items from the list while iterating over it. Don't do that -- the memory is shifting as you're trying to access it.

Removing all the 'a's is a task well-suited for filter() or a list comprehension:

n = 0
a_list = ['a','p','l','e']
a_list.insert(1,'a')
a_list.insert(3,'p')
print(list(filter(lambda x: x != 'a', a_list))) # filter()
print([char for char in a_list if char != 'a']) # list comprehension
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • 1
    This is exactly what I was writing just a second ago. It's really crucial not to delete values while iterating over them if you don't have control over it. In Python list object is not a static array, so inserting/deleting while iterating will be dangerous since it'll cause jumps and dynamic movements. @BrokenBenchmark – baymurat Jan 09 '22 at 02:23