1

I would like to write a program that excludes every string from a list.

lst =  ["a", "e", "i", "o", "u"]
for i in lst:
 if isinstance(i, str):
   lst.remove(i)
print(lst)

I would like to know why the result of the above code is['e', 'o'].

solid.py
  • 2,782
  • 5
  • 23
  • 30
  • When you remove the first element of the list (`a`), the second element of the list becomes `i`, which you remove and then the third element of the list is `u`, which you remove, leaving you with `['e', 'o']` – Nick Mar 15 '20 at 23:21

2 Answers2

4
for i in lst.copy():

Iterate over a copy of the data if you want to change it.

Boergler
  • 191
  • 1
  • 5
1

With a slight modification, this works as expected. Basically lst[:] creates a slice of the original list that contains all elements. For more information on the slice notation, see this wonderful answer in Understanding slice notation

lst =  ["a", "e", "i", "o", "u"]
for i in lst[:]:
 if isinstance(i, str):
   lst.remove(i)
print(lst)

When run this outputs an empty list:

[]
solid.py
  • 2,782
  • 5
  • 23
  • 30