-1

I'm having trouble understanding how 'for loop' works in Python. I want to remove a character from a list using for loop to iterate through the list but the output is not as expected. In the following code I want to remove the character 'e':

lista = ['g', 'e', 'e', 'k', 'e','s', 'e', 'e']

for x in lista:
 if x == 'e':
   lista.remove(x)

print(lista)

It prints ['g', 'k', 's', 'e', 'e'] when I was expecting ['g', 'k', 's'].

Thank you.

VladETC
  • 19
  • 3
  • 1
    Modifying a sequence while you iterating it will not work as you expected. How about make another copy that filter what you need. `new_list = [x for x in lista if x != e]` – falsetru May 23 '20 at 23:45

6 Answers6

2

You cannot remove things from a list when you iterate over it. This is because when you remove an item from the list it shrinks. So what's happening is that when you encounter an 'e', the list is shrunk and you go to the next item in the list. But since the list shrunk, you're actually jumping over an item.

To solve your problem, you have to iterate over copy of your list.

lista = ['g', 'e', 'e', 'k', 'e','s', 'e', 'e']

for x in lista.copy():
   if x == 'e':
      lista.remove(x)

print(lista)
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
0

You can use the following code

lista = ['g', 'e', 'e', 'k', 'e','s', 'e', 'e']

for i in range(0, len(lista)):
    element = lista[i]
    if element == 'e':
        del lista[i]

The above approach will modify the original list.

A far more simpler and better way is as follows:

list(filter(('e').__ne__, lista))

Both the methods return

['g', 'k', 's']

bigbounty
  • 16,526
  • 5
  • 37
  • 65
0

A solution to your problem may be this :

while 1:
    try: 
        lista.remove("e")
    except ValueError:
        break
Wassel
  • 98
  • 9
0

The simple list comprehension. The idea is to not update the list while iterating.

lista = ['g', 'e', 'e', 'k', 'e','s', 'e', 'e']
lista = [i for i in lista if i!='e']
mad_
  • 8,121
  • 2
  • 25
  • 40
0

When you remove an item from a List it gets updated. Therefore shrinking it. Thus, in your case when first two of the e's are removed, last two elements are not taken into consideration.

What you need to do is to check if the the element still exists-

lista = ['g', 'e', 'e', 'k', 'e', 's', 'e', 'e']
while 'e' in lista:
    lista.remove('e')
print(lista)

UPDATE:

As @mad_ pointed out, you can reduce the complexity by-

lista = ['g', 'e', 'e', 'k', 'e', 's', 'e', 'e']
print([i for i in lista if i != 'e'])
kartoon
  • 1,040
  • 1
  • 11
  • 24
  • This will perform terribly in large lists. Your algorithm has a time complexity of O(n**2) which can easily be improved – mad_ May 23 '20 at 23:51
0

I think the most pythonic way is to do it using list comprehension as shown below:

lista = ['g', 'e', 'e', 'k', 'e','s', 'e', 'e']

lista = [x for x in lista if x != 'e']
print(lista)

The reason why your method is not working is because you cannot remove items from a list whilst iterating over it, as you will be changing the indexes of each object in the list.

Apie
  • 95
  • 5