-1

In python, I created this simple code:

a = [1, 2, 3, 'hi', 'dog']
for item in a:
  if type(item)==str:
    a.remove(item)
print(a)

I want the output to be:

[1, 2, 3]

But for some reason the output is showing as:

[1, 2, 3, 'dog']

Can someone please tell me what I am doing wrong?

Jon Smith
  • 155
  • 1
  • 3
  • 7
  • Don't modify a collection while also iterating over it. If you do that, you can expect unexpected behavior. Instead of modifying the original list, do it the Python way, and create a new list containing only the items you want to retain. – Paul M. Jun 29 '20 at 19:07

1 Answers1

0

If you don't mind creating a new list:

a = [1, 2, 3, 'hi', 'dog']
a = [x for x in a if not isinstance(x,str)]
print(a)
farbiondriven
  • 2,450
  • 2
  • 15
  • 31