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

How to remove list within a list using conditional and type()?

Why doesn't "is not" not catching the list [1,2,3] ??? I passed by hardcoding the .remove but it feels dirty! Can somebody please tell me what's wrong?

use .remove() and/or del to remove the string, the boolean, and the list from inside of messy_list. When you're done, messy_list should have only integers in it.

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

for item in messy_list:
    if type(item) is not int:
        messy_list.remove(item)

#messy_list.remove([1,2,3]) - cheating!!!!!

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

messy_list.remove([1,2,3])

print(messy_list)

1 Answer

Anibal Marquina
Anibal Marquina
9,523 Points
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]

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

You can use 'is not' as you stated before for overcoming the challenge.. but I had to be sure that the loop was iterating over the whole list...range(0, len(messy_list)). Without that line of code as you said the integers 2 and 3 are not removed from messy_list, also the same happened once with the boolean...

I tried this code also with the rest of the data types you can change the code to (bool,str,int or list) and is working

Cheers

Thanks; you rock!