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

Snir Lugassy
Snir Lugassy
1,824 Points

List type pass type-checking for int (type(item) == int)

Hi, I am looping through messy_list and checking types if items with: if type(item) == int

But lists still pass the type checking and wouldn't remove from the list

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
one = messy_list.pop(messy_list.index(1))
messy_list.insert(0, one)

for item in messy_list:
    if type(item) is int:
        continue
    messy_list.remove(item)

1 Answer

Hi there!

Nice solution! The problem is that you're modifying the same list you're looping through. When an item is removed from the list, the list becomes shorter, so it has the effect of the for loop skipping the next item in the list (say you remove the first item in the list, when the for loop goes to the second, it will actually be the third item in the original list).

The most common solution is to loop through a copy of the list. To do this just add "[:]" to your for line:

for item in messy_list[:]:
    if type(item) is int:
        continue
    messy_list.remove(item)