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 trialVladyslav Koroviakovskyi
5,049 Pointsthe condition i used to remove all elements except ints from the list does not remove a list inside the list
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] messy_list.insert(0, messy_list.pop(3))
for item in messy_list: if type(item) != int: messy_list.remove(item)
in the preview, I can see that the output of the function is a list with a list in the end: [1, 2, 3, [1, 2, 3]]
why my condition does not remove a inside list from a list?
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
for item in messy_list:
if type(item) != int:
messy_list.remove(item)
# Your code goes below here
1 Answer
Steven Parker
231,269 PointsInternally, the loop keeps track of which item it is working with by its index. Each time through the loop, the index is incremented and the next item is retrieved.
If you remove an item from the list while the loop is running, the index numbers of the remaining items changes; and that causes the loop to skip the next one in the sequence.
The copy does not change as the loop runs, so every item is checked.
Vladyslav Koroviakovskyi
5,049 PointsVladyslav Koroviakovskyi
5,049 Pointsok, i just figured out, I changed the line: for item in messy_list.copy() so, it iterates though a copy, and it worked. can someone explain why i need copy() to make this work, please