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 trialRay C
1,220 PointsWhy doesn't this code remove the list if its type is list?
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3)) for item in messy_list: if type(item) != int: messy_list.remove(item) print(messy_list)
print(messy_list) returns: [1, 2, 3, [1, 2, 3]]
2 Answers
Steven Parker
231,275 PointsAltering an iterable inside a loop that it is controlling can cause undesired behavior, such as skipping over items or using them twice.
Always use a copy of an iterable to control a loop if the loop will be making changes to it.
Vincent Cegers
1,248 PointsHa! Awesome thank you.
Vincent Cegers
1,248 PointsVincent Cegers
1,248 Pointshey, Steven sorry to bother you again. I am having this same issue even when using a copy could you help me with my code.
messy_list1 = messy_list.copy()
for x in messy_list1:
print(messy_list1)
Steven Parker
231,275 PointsSteven Parker
231,275 PointsMaking messy_list1 and using it for the loop was a good idea, but you're also removing items from it. The "remove" needs to be applied to the original "messy_list".
Steven Parker
231,275 PointsSteven Parker
231,275 PointsRay C — did this answer your question?