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
jimmy fallon
Courses Plus Student 306 PointsPython for loop
In the following code why does the list still contain items?
my_list = ['mangoes', 'bananas', 'oranges', 'juice']
for item in my_list: my_list.remove(item)
my_list ['bananas', 'juice']
1 Answer
Jason Anello
Courses Plus Student 94,610 PointsHi Jimmy,
Your code example illustrates the problem with removing or adding items to a list while you're iterating over it.
The first time through the loop, python needs to retrieve the item at index 0. This is 'mangoes' and it is removed.
The next time through the loop it needs to retrieve the item at index 1. This should have been 'bananas' but 'bananas' moved into the 0 index spot vacated by 'mangoes' and 'oranges' moved into the index 1 spot. So it ends up grabbing 'oranges' at index 1 and 'bananas' is skipped entirely.
'juice' then occupies the spot 'oranges' was in. Then it stops because the next index is 2 and there is no longer an item at index 2. The list has a length of 2 at this point.
If your goal is to remove all of the items in the list then you could use a list slice which would create a copy of the list. This way you can iterate over the copy and remove items from the original list.
my_list = ['mangoes', 'bananas', 'oranges', 'juice']
for item in my_list[:]:
my_list.remove(item)
my_list should be empty now.
Dustin Knudsen
1,616 PointsDustin Knudsen
1,616 PointsInteresting!