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 trialCoffee Li
Courses Plus Student 2,229 Pointswhat'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)
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
231,269 PointsInside 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.
Coffee Li
Courses Plus Student 2,229 PointsI thought the list should be mutable per se
Steven Parker
231,269 PointsThe 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.
Coffee Li
Courses Plus Student 2,229 Pointshow to copy a list ? can you explian a bit more thanks so much
Steven Parker
231,269 PointsWe'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!).
Coffee Li
Courses Plus Student 2,229 PointsThanks Steven