Search code examples
pythonlistdata-structuresdel

what is the order of python insert and del ? when I am trying to manipulate an element simultaneously


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'


Solution

  • 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