0

I'm attempting to create a function that returns only the integers in a given list. My main issue is that every time I run the code the program only removes every other string.

I've tested this multiple times and have confirmed that the output is always equal to every other string in the list, obviously ignoring the integers because they aren't strings.

> def filter_list(l):
>     for ele in l:
>         if isinstance(ele, str):
>             l.remove(ele)
>     return l
> 
> print(filter_list([1,3,2,'aasf','2312','1', 'g', 'c', 'b','c','123',123]))

This particular list I tried gave me the output of

>[1,3,2,'2312','g','b','123',123]

After reading the immediate comments I solved the issue. Thank you all for letting me know, I'm only a couple weeks into programming so I'll make note not to modify the same list I'm iterating!

Dan Cool
  • 11
  • 1
  • You shouldn't modify the list as you iterate it. It causes all the the elements to shift. Look at what values of `ele` you get, and you'll see what I mean – Alexander Jul 26 '22 at 23:37
  • Don't change/alter/remove the list item while looing it, the index will be off. It's one of the common errors. – Daniel Hao Jul 26 '22 at 23:37
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 26 '22 at 23:38
  • `list(filter(lambda x: not isinstance(x, str), test_list))` – Paul H Jul 26 '22 at 23:43

0 Answers0