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

Morten Egge
Morten Egge
1,898 Points

For loop stops

I have tried several combination's but when the for loop is finished there is still a list with integers left instide the list.

Anyone that knows what’s wrong and what’s going on ?

lists.py
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 not type(i) is int:
        messy_list.remove(i)

2 Answers

Anibal Marquina
Anibal Marquina
9,523 Points
for _ in range(0, len(messy_list)):   
    for i in messy_list:
        if not type(i) is int:
            messy_list.remove(i)
Anibal Marquina
Anibal Marquina
9,523 Points

Hi there..

If you want to do it using loop logic you will have to be sure your loop runs until the end of your list adding for _ in range(0, len(messy_list)):

That works to overcome the challenge but you must try to do it using Del and Remove() methods, that will make you aware how the list mutates and how the index of the elements changes every time you erase an item from the list.

Morten Egge
Morten Egge
1,898 Points

Thank you.

Though I had already figured out that I needed a second loop outside. I still don't understand what's going on...

What do you mean "Have to use Remove and Del methods" ? "Hard Coding" the actual index numbers ?

Anibal Marquina
Anibal Marquina
9,523 Points

Hi.. yes basically hard coding the index..