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

Python Introducing Lists Using Lists Mutability

Bruno Correia
Bruno Correia
3,114 Points

Why is "sword" and "boomerang" left when deleting while iterating?

So I understand that to be able to delete all items on the list, we need to make a copy of the list so all items are actually deleted. I don't quite understand why, however. What makes the following not work as we expect it to? Looking at the code, as Craig said, it makes total sense to do it like this. What causes it not to work?

for item in inventory:
    inventory.remove(item)

2 Answers

Similar question is already answered here: https://teamtreehouse.com/community/why-doesnt-listremove-removes-all-the-elements-after-using-a-for-in-loop-but-using-loop-in-for-listcopy-does

If you are still in doubt, ask in comments. I will surely try to help you.

Bruno Correia
Bruno Correia
3,114 Points

Ohh, thank you! I promise I tried to search first but missed that one somehow :-P The reply there was very helpful, thank you for pointing it out