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

Why 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
Steven Parker
229,744 Points

Altering 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.

hey, 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:

if type(x) is str or type(x) is bool or type(x) is list:

    messy_list1.remove(x)

print(messy_list1)

Steven Parker
Steven Parker
229,744 Points

Making 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". :wink:

Steven Parker
Steven Parker
229,744 Points

Ray C — did this answer your question?

Ha! Awesome thank you.