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

what's wrong with code below, it fails everytime

messy_list.insert(0, messy_list.pop(3))

for i in messy_list:
    if type(i) != int:
        messy_list.remove(i)
lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here

messy_list.insert(0, messy_list.pop(3))

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

4 Answers

Steven Parker
Steven Parker
231,269 Points

Inside a loop, if you alter the loop's source of iteration you can cause side effects like items being skipped over. There are several ways to prevent this, one simple one would be to use a copy of the original item as the iteration source.

I thought the list should be mutable per se

Steven Parker
Steven Parker
231,269 Points

The mutability is what causes the trouble. Since you can modify the list while the loop is running, the loop can get confused about which element to select during the next pass.

how to copy a list ? can you explian a bit more thanks so much

Steven Parker
Steven Parker
231,269 Points

We're getting ahead of the course here, but one way to copy a list is by using a slice with no arguments, in this case "messy_list[:]". Slices are explained later in the courses.

But you really don't need a loop at all to pass the challenge. You can do it with just a few remove or del statements (or even a few pop statements!).

Thanks Steven