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
femmebot
8,416 PointsWhy doesn't type() work to remove all list items that were not integers?
For the list manipulation exercise, when going through each list item, it identifies [1,2,3] correctly as a list but when running the for-in loop, it keeps it intact.
the_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for item in the_list:
if type(item) is not int:
the_list.remove(item)
2 Answers
Matthew Rigdon
8,223 PointsYou need to make a copy of the_list.
Here is what I did:
the_list = ["a", 2, 3, 1, False, [1, 2, 3]]
the_list_copy = ["a", 2, 3, 1, False, [1, 2, 3]]
for item in the_list:
if type(item) is not int:
the_list_copy.remove(item)
Notice how my code only modifies the new list. In Python, it is a good habit always to copy lists that you are modifying. The reason we do this is because a For loop will start at the index of 0 (in this case 'a') then move to the index of 1, index of 2, etc. The original code deleted the 'a' at index 0, then moved onto index 1.
Now your list looks like this:
the_list = [2, 3, 1, False, [1, 2, 3]]
Now what is at the index of 1? The '3' value is. It skipped over '2' because you modified the original list. The type(item) works. The issue was that your list of [1, 2, 3] was never tested at all due to Python assuming your list was finished.
femmebot
8,416 PointsAh, of course. Thank you!