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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Stanisław Dudzik](https://uploads.teamtreehouse.com/production/profile-photos/9992942/micro_amat.jpg)
Stanisław Dudzik
9,731 PointsHow to iterate over a list and remove elements of particular types from it? Using for loop does not work.
Hi. We are supposed to get rid of strings, bools and lists of a messy_list. I am checking for elements index in the list, then check if element is not an integer using type(e) != int and oif it is not an integer try to remove it from the list by messy_list.remove(position_index). What is wrong with using for loop here and what is the alternative? Could i use While loop for a set of elements (we learned that it is not what they are for).
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
# Your code goes below here
for e in messy_list:
position_index = messy_list.index(e)
if type(e) != int:
messy_list.remove(position_index)
1 Answer
![Krishna Pratap Chouhan](https://secure.gravatar.com/avatar/8c46996a3e9af1329e084ea8434377ea?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Krishna Pratap Chouhan
15,203 Pointsmessy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
# Your code goes below here
for e in messy_list:
if type(e) != int:
messy_list.remove(e)
Remove removes the element.
but,
.
.
current output is : [1, 2, 3, [1, 2, 3]] i think it should be: [1, 2, 3]
.
thinking...
Got it... list is changing and thats why for loop is behaving unexpectedly.
for more details... https://stackoverflow.com/questions/6500888/removing-from-a-list-while-iterating-over-it
This should solve the problem.
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
# Your code goes below here
for e in messy_list:
if type(e) != int:
messy_list.remove(e)
messy_list = list(messy_list)
Krishna Pratap Chouhan
15,203 PointsKrishna Pratap Chouhan
15,203 Pointslogging my IDLE...
Krishna Pratap Chouhan
15,203 PointsKrishna Pratap Chouhan
15,203 PointsKenneth Love help please.