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

Messy_list elegant solution

I've spent two hours trying to figure this out on my own. I solved the messy_list problem by typing the three lines:

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

The first thing that comes to mind (for each element in the list if it isn't integer just remove it) just doesn't work and I don't understand why. I know by now that it has something to do with False being part of the list.

In these two examples the interpreter removes False and then stops iterating.

for element in messy_list:
    if type(element) != int:
        messy_list.remove(element)

for element in messy_list:
    if type(element) != int:
        del messy_list[messy_list.index(element)]

This means that del/index and remove dont have trouble with the arguments that are given. I then went ahead to see what the script does in each step with

for element in messy_list:
    print("{} is of type {}".format(element,type(element)))
    if type(element) == int:
        pass
    else:
        print("I will now remove {}".format(element))
        messy_list.remove(element)

The output is

a is of type <class 'str'>
I will now remove a
3 is of type <class 'int'>
1 is of type <class 'int'>
False is of type <class 'bool'>
I will now remove False

If I alter the list to contain everything but the boolean or keep doing the procedure more often than necessary eventually (after the boolean is gone) it will do as I expect it too.

Now in hindsight: Why isn't the code doing what I'm expecting it to do? What does the Boolean have to do with it? And how would a clean and nice solution to the problem look like?