Tharaka Kodithuwakku
last year
Tharakacountry asked

Are animals2 = animals1.copy() and animals2 = animals1 the same?

Kelish Rai
Expert
last year
Kelish Rai answered

No, animals2 = animals1.copy() and animals2 = animals1 are not the same. There’s a key difference in how they work, and I’ll explain with simple examples.

1. Copying directly:

animals1 = ['dog', 'cat']
animals2 = animals1

# Change the first element of animals2 to 'rabbit'
animals2[0] = 'rabbit'

print(animals1)    # Output: ['rabbit', 'cat']
print(animals2)    # Output: ['rabbit', 'cat']

In this case, when you change the first element of animals2 to "rabbit", you’ll notice the change also appears in animals1.

That’s because animals2 = animals1 doesn’t create a new list. Instead, animals2 just references the same list as animals1.

So, when you modify one, it affects the other.

2. Copying using copy():

animals1 = ['dog', 'cat']
animals2 = animals1.copy()

# Change the first element of animals2 to 'rabbit'
animals2[0] = 'rabbit'

print(animals1)    # Output: ['dog', 'cat']
print(animals2)    # Output: ['rabbit', 'cat']

In this case, animals2 = animals1.copy() creates a new independent copy of the list. Modifying animals2 does not affect animals1 because they are now two separate lists in memory.

In short:

  • animals2 = animals1 makes animals2 reference the same list as animals1. Changing one will affect the other.

  • animals2 = animals1.copy() creates a new, independent copy of the list, so modifying one list will not affect the other.

Python
This question was asked as part of the Getting started with Python course.