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?
list1andlist2are references to the same mutable list in first example