1

I'm trying to remove all elements within a list except those that are integers. I am able to remove strings and booleans but I am unable to remove lists given the code below.

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

for idx, val in enumerate(messy_list):
    if type(val) != int:
        messy_list.pop(idx)

print(messy_list)
mattbeiswenger
  • 383
  • 3
  • 11

2 Answers2

1

How about a functional approach?

>>> messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> filter(lambda x: type(x)==int, messy_list)
[2, 3, 1]
Pavel
  • 7,436
  • 2
  • 29
  • 42
0

The problem is not the sub-list, but the fact that you're modifying your original list while you're iterating it.

Iterate a copy instead:

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

for val in list(messy_list):
    if type(val) != int:
        messy_list.remove(val)

print(messy_list) # [2, 3, 1]
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50