3

This is my first question ever - sorry if bit trivial

I wonder what is the difference (is there any?) between this two methods

Method A

animals = ['cat', 'dog', 'goldfish']  
pets = animals[:] 

animals.sort()
pets.append('donkey')

print(animals)
print(pets)

Method B

animals = ['cat', 'dog', 'goldfish']
pets = list(animals)

animals.sort()
pets.append('donkey')

print(animals)
print(pets)

In method A copy of list is created and assigned to new variable (pets)

In method B new list is created and assigned to pets?

(not sure if I'm right) Do we creating list in method A ?

michal w
  • 119
  • 7

1 Answers1

0

Both will copy the list stored in the animals variable and assign it to pets variable. The copy is by value and not by reference, so changing an item in the list assigned to pets won't change the list assigned to animals and vice-versa

galfisher
  • 1,122
  • 1
  • 13
  • 24