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

Hara Gopal K
PLUS
Hara Gopal K
Courses Plus Student 10,027 Points

if type(x) not int: remove items from a python list

for the collection code challenge, i tried the following:

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)

though the inner list is not of type int, it is still being retained. I solved this differently but would like to know what's going on here...

1 Answer

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

it is only being retained by chance. the problem is that you are modifying a list that you are looping through, which is resulting in skipped elements. the loop starts at index 0, it's an 'a', removes it, but the remove method shifts remaining elements to the left. the loop however moves on to index 1, so it is not actually even considering the 2 in the list, because after the removal of 'a', 2 is now at index 0, but the loop is looking at index 1, which is the 3. the same skipping happens when the loop hits the false, it is removed and the internal list is shifted left, but the loop counter moves on past the internal list to the end and the loop exits. the internal list is skipped and is not considered at all, so that's why it stays despite not being an int. to fix you can make a copy and loop through that while modifying the original, or vice versa. this will ensure that every element is considered and nothing is skipped, and results in a list with only ints inside.