Python Python Collections (2016, retired 2019) Lists Removing items from a list

How to iterate over a list and remove elements of particular types from it? Using for loop does not work.

Hi. We are supposed to get rid of strings, bools and lists of a messy_list. I am checking for elements index in the list, then check if element is not an integer using type(e) != int and oif it is not an integer try to remove it from the list by messy_list.remove(position_index). What is wrong with using for loop here and what is the alternative? Could i use While loop for a set of elements (we learned that it is not what they are for).

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))

# Your code goes below here
for e in messy_list:
    position_index = messy_list.index(e)
    if type(e) != int:
        messy_list.remove(position_index)

1 Answer

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
# Your code goes below here
for e in messy_list:
    if type(e) != int:
        messy_list.remove(e)

Remove removes the element.

but,

.

.

current output is : [1, 2, 3, [1, 2, 3]] i think it should be: [1, 2, 3]

.

thinking...

Got it... list is changing and thats why for loop is behaving unexpectedly.

for more details... https://stackoverflow.com/questions/6500888/removing-from-a-list-while-iterating-over-it

This should solve the problem.

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
# Your code goes below here
for e in messy_list:
    if type(e) != int:
        messy_list.remove(e)
        messy_list = list(messy_list)

logging my IDLE...

>>> messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> print(len(messy_list))
6
>>> messy_list.insert(0, messy_list.pop(3))
>>> print(messy_list)
[1, 'a', 2, 3, False, [1, 2, 3]]
>>> print(len(messy_list))
6
>>> # Your code goes below here
... for e in messy_list:
...     position_index = messy_list.index(e)
...     print(e)
...     if type(e) != int:
...         messy_list.remove(e)
...
1
a
3
False
>>> print(messy_list)
[1, 2, 3, [1, 2, 3]]
>>> print(len(messy_list))
4
>>>

Kenneth Love help please.