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 (Retired) Lists Redux Manipulating Lists

Why wouldn't this code work?

the_list = ["a", 2, 3, 1, False, [1, 2, 3]]

for item in the_list: if type(item) is str or type(item) is bool or type(item) is list: the_list.remove(item)

The last item(the list) still remains. I don't understand, what am I doing wrong?

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Akshat Jain Hi, You can't just iterate though a list while removing item from it, because it change the length of the list. well, technically Python won't stop you from doing that, but the result won't be what your expected.

In your for loop, when it runs, it will assign each element in the_list to item and execute the loop body for each.

In the first run of for loop, the first item in the_list "a" was assigned to item, but in the loop body, you remove it from the_list; so in the next run of your loop, the 2nd item in the new list [2, 3, 1, False, [1, 2, 3]], which is 3, got assigned to item. You see the problem here? 2 was never checked due to the length change of the the_list. You should be able to see why your end result included unwanted item.

I think for this code challenge, it only ask you to manually remove the item from the list one by one using .remove() and/or del. So I suggest you just hand code it, and don't try anything too fancy.

the_list.remove("a")
the_list.remove(False)
the_list.remove([1,2,3])

Thanks! That solved my doubt