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 trialJoel Ulens
3,101 PointsI do not understand what copy() does. I have looked at the documentation of copy, and yet I do not know why he uses it.
at 6:10 he uses the copy method. I am not sure what he does. AFAIK copy simply gives a copy of a value, however, why would he need that, couldn't he just put self.append(value) instead of self.append(copy.copy(value))
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsThe short answer is all variables are actually pointer to objects in the "heap of objects". When you assign one variable to another, a new object isn't created. Instead, a new pointer to the same object is created.
When assigning an existing object into a list, only a new pointer to that object is included in the list. A side effect of this is if the object being pointed to in the list is altered, then every pointer to that same object will also see the same change because there is only one object to be changed.
By using copy()
, a new copy object is created in the "heap", then a pointer to this new independent copy is used.
Post back if you need more help. Good luck!!!
Andrew Fellenz
12,170 PointsChris Freeman, what an incredibly helpful example. Thank you!
Tyler Wells
Python Development Techdegree Student 2,678 PointsTyler Wells
Python Development Techdegree Student 2,678 PointsChris Freeman so in the case in this video it may not have been necessary to use
copy
but we did it just as a good habit to get into in case we eventually want to change the original object?Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsGood question Tyler. If you want each of the filled items to be independent of the original value and not the same object, then a copy is needed. If a copy isn't used, then a change in the FilledList item would also change the original value. Without the copy, the follow could happen.
Here, both new_list items changed since they were both a reference to the object
a
. Using a copy fixes this: