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 trialAlex Rosier
Courses Plus Student 648 PointsI am using the type() function to identify data types in list and remove by type. Why does this fail for inner list?
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
Your code goes below here
messy_list.insert(0, messy_list.pop(3))
for item in messy_list: if type(item) is str: messy_list.remove(item) elif type(item) is bool: messy_list.remove(item) # Why does the below fail to execute? elif type(item) is list: messy_list.remove(item) else: pass
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
# Your code goes below here
messy_list.insert(0, messy_list.pop(3))
for item in messy_list:
if type(item) is str:
messy_list.remove(item)
elif type(item) is bool:
messy_list.remove(item)
# Why does the below fail to execute?
elif type(item) is list:
messy_list.remove(item)
else:
pass
1 Answer
Steven Parker
231,236 PointsRemoving items from an iterable while it is controlling a loop can cause other items to be skipped. To avoid this, you can use a copy of the iterable to control the loop.
Also, you can simplify things by removing anything that's not what you want instead of each explicit other type:
for item in messy_list.copy():
if type(item) is not int:
messy_list.remove(item)