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

austin bakker
austin bakker
7,105 Points

finding list within a list and removing it with a loop

I am trying to remove items using this loop. But i can not seem it remove the list within the list i tried the .remove function, and had no success same with the index function. what am i missing in my code?

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
messy_list.insert(0,1)
messy_list.pop(4)
remove_from_list=["a", False, [1, 2, 3]]
for list_item in messy_list:
    if list_item in remove_from_list:
        del messy_list[messy_list.index(list_item)]
    else:
        continue

1 Answer

Chris Jones
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Jones
Java Web Development Techdegree Graduate 23,933 Points

Hey Austin,

This is because as you're looping through messy_list, you're removing items from messy_list, so the collection is being changed during your loop. If you remove too many items, python will begin the loop for the next item in the list and will realize that it's run out of items in the list.

Try cloning messy_list to new list object and iterating through that list, but removing items from messy_list like so:

messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.pop(3)
messy_list.insert(0,1)

new_list = list(messy_list)  # clone messy_list
for item in new_list:  # and iterate/loop over the new_list
    if not type(item) is int:  # check if item is not of type int
        messy_list.remove(item) # remove item from messy_list, NOT new_list so that the iteration/loop is not is not changed

I know it can be a confusing concept, but it might make more sense if you step through the code in Pycharm's debugger.

Let me know if you have any more questions! I hope this helped!