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

What makes copy.copy better?

What makes copy.copy better than just assigning the contents of one variable to another?

Hi Keifer,

Are you asking, why do this?

>>> import copy
>>> list1 = [1, 2, 3]
>>> list2 = copy.copy(list1)

If you can do this?

>>> list1 = [1, 2, 3]
>>> list2 = list1

1 Answer

It all depends on whether you want 2 independent copies of that list or not.

In the second example, you're not creating a copy of the list. list1 and list2 are both a reference to the same list in memory. You can change the list using either variable.

Here's some python output:

>>> list1 = [1, 2, 3]
>>> list2 = list1
>>> list1 is list2
True
>>> list2[2] = 10
>>> list2
[1, 2, 10]
>>> list1
[1, 2, 10]
>>>

The is operator checks to see if 2 objects have the same identity. Getting back True tells us that both of those list variables are referencing the same list in memory. After changing the list using list2 we can see that list1 shows the same change. This is because there is only 1 copy of that list in memory.

Repeating again using copy.copy:

>>> import copy
>>> list1 = [1, 2, 3]
>>> list2 = copy.copy(list1)
>>> list1 is list2
False
>>> list2[2] = 10
>>> list2
[1, 2, 10]
>>> list1
[1, 2, 3]
>>>

Here we can see that the is operator returns False. This means the 2 objects do not have the same identity because there are now 2 copies of this list in memory. list1 references 1 of these copies and list2 references the other copy.

When list2 is modified, we can see that the change shows up in list2 but list1 still maintains the original values it was assigned. This shows that you have 2 independent copies of the list in memory and they can be manipulated independently of each other.

Okay that makes sense. I had the wrong idea that when you assign one variable another changing one wouldn't change the other. That's not very logical the more I think on it.

Thank you for your help!