0

in lists there is this feature called ".copy()". However I am a bit confuse whether to use ".copy()" over "=" and vice versa since both act exactly the same. Here is an example:

friends = ["Tom", "holland", "Steves", "Jim", "Jimmy", "Boy"]
friends2 = friends.copy()
print(friends2)
print(friends)

and the result obtain is this:

['Tom', 'holland', 'Steves', 'Jim', 'Jimmy', 'Boy']
['Tom', 'holland', 'Steves', 'Jim', 'Jimmy', 'Boy']

and if you use "=" instead of ".copy()", you get the same result. Example:

friends = ["Tom", "holland", "Steves", "Jim", "Jimmy", "Boy"]
friends2 = friends
print(friends2)
print(friends)

you get the same result.

So is there any differences in the both keyword. If there is which one should I use in different situations.

Aces
  • 11
  • 2
  • 5
    You will notice the difference if you try appending or changing something in `friends`. With `=` you only have one list in memory. Changes will be reflected in both `friends` and `freinds2` since they are the same list. – Mark Oct 23 '20 at 14:34
  • just update a value in list in both case and print, you will find the difference, value in both list will be remain same in `=` case and `copy` case it will change only in 1 case – sahasrara62 Oct 23 '20 at 14:38
  • just update a value in one list in both case and print, you will find the difference, value in both list will be remain same in `=` case and `copy` case it will change only in 1 case – sahasrara62 Oct 23 '20 at 14:38
  • It is true but why is that so – Aces Oct 23 '20 at 14:45
  • For example if you change in friends2 and did not change in friends, why does friends also change – Aces Oct 23 '20 at 14:46
  • Because when you say `a = b`, you are NOT making another copy of b; you are just assigning `a` as another _name_ for `b`. – John Gordon Oct 23 '20 at 15:01

0 Answers0