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 trialStanisł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
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.