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

Mutability

could someone help me understand the copy method on a loop as I am still experiencing difficulties on it. so if you use a copy method on a loop it remains the same whilst iterating through the list rather than using the original that modifies it. but how does it modify and how does the copy method remain the same when iterating through

2 Answers

Steven Parker
Steven Parker
231,269 Points

Copying the list doesn't cause it to be modified. What's most likely happening is that some code in the loop body is modifying the loop iterator. Changing that while the loop is running can confuse things and cause unexpected behavior (like items skipped or handled twice).

Making a copy before the loop begins and using the copy as the iterator allows you to make changes to the original in the loop body without affecting the loop behavior.

Shanil Mohan R
Shanil Mohan R
1,506 Points

The copy method on a list creates a separate copy of the list. This copy has a different memory address. During the for loop this copy is untouched and it is only used to iterate through the original list and remove each item from the original list and eventually the original list becomes empty.