samedi 28 novembre 2020

Removing elements from list using if condition

I have tried to remove an element by using if condition in a list, if the list is like this

list1 = ['a','1','c','2','d','3']

for i in list1:
    if i == 'a' :
        list1.pop(list1.index(i) - 1)
        list1.remove(i)

print(list1)

Output : ['c', '2', 'd', '3']

It removes all 'a' in the list but when 'a' is near another 'a', its not removing the second 'a',

list1 = ['a','1','a','2','d','3']

for i in list1:
    if i == 'a' :
        list1.pop(list1.index(i) + 1)
        list1.remove(i)

print(list1)

Output : ['a', '2', 'd', '3']

Why is that ? I want to remove both 'a'. Any ideas ?

Aucun commentaire:

Enregistrer un commentaire