Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.