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']
.
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']
.
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:
[]