As we know to copy list we have to copy() method, otherwise changes of values could happen. Just like this one:
1st CODE:
list1 = ['a', 'b', 12]
list2 = list1
print('List1: ',list1)
print('List2: ',list2)
list2.append('new_val')
print('Updated_List1: ',list1)
print('Updated_List2: ',list2)
It's O/P:
List1: ['a', 'b', 12]
List2: ['a', 'b', 12]
Updated_List1: ['a', 'b', 12, 'new_val']
Updated_List2: ['a', 'b', 12, 'new_val']
Above code i got it. BUT IF WE DO LIKE THIS(below code):
2nd CODE:
list1 = ['a', 'b', 12]
list2 = list1
list3 = ['x','y','z']
list2 = list2 list3
print('List1: ',list1)
print('List2: ',list2)
print('List3: ',list3)
IT's O/P:
List1: ['a', 'b', 12]
List2: ['a', 'b', 12, 'x', 'y', 'z']
List3: ['x', 'y', 'z']
Here you can see, 1st code: changes in list2 affects list1 too. But in 2nd code: it's not happening. Can anyone explain why is this happening or i'm missing something?
CodePudding user response:
In first code, list2 is just a reference of list1, hence change in list2 affects list1.
Type id(list1)
and id(list2)
, they should be the same in case of first code implying that list1
and list2
have the same address in the memory and they are the same (The id(object)
prints the memory location of the object in python).
In the second code, that's not the case. The statment list2 = list2 list3
creates a new copy of list2 in memory. Checking for id(list1)
and id(list2)
will be different now.
Maybe checking the docs for copy will be helpful.
CodePudding user response:
You can also do
list1 = [ *list2 ]
to copy items of list2
to list1
. It creates a new list object having the items of list2
then assigns to list1
N.B: Don't use it for nested lists