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 Object-Oriented Python Advanced Objects Subclassing Built-ins

Joel Ulens
Joel Ulens
3,101 Points

I 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
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

The 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!!!

Chris 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
Chris Freeman
Treehouse Moderator 68,426 Points

Good 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.

>>> a = [1, 2, 3]
>>> new_list = [a, a]
>>> new_list
[[1, 2, 3], [1, 2, 3]]
>>> new_list[0][1] = 5
>>> new_list
[[1, 5, 3], [1, 5, 3]]

Here, both new_list items changed since they were both a reference to the object a. Using a copy fixes this:

>>> a = [1, 2, 3]
>>> new_list = [a.copy(), a.copy()]
>>> new_list
[[1, 2, 3], [1, 2, 3]]
>>> new_list[0][1] = 5
>>> new_list
[[1, 5, 3], [1, 2, 3]]
Andrew Fellenz
Andrew Fellenz
12,170 Points

Chris Freeman, what an incredibly helpful example. Thank you!