0
why does append function affect other list?
ā-LISTSā- list1=[1,2,3,4] list2=list1 list1.append(5) print(list2) Result:[1,2,3,4,5] ā-VARIABLESā- a=2 b=a a+=1 print(b) Result:2
2 Answers
+ 7
the statement list2 = list1 assigns the variable list2 to the reference of list2(meaning list2 points to list1) so if list1 changes list2 will similarly change since it is actually a reference to list1 and not a new list
+ 1
Iāve tried
list1=[1,2,3,4]
list2=[1,2,3,4] #1
list1.append(5)
print(list2)
But it returns [1,2,3,4]
On #1 what is the difference when i write list2=list1 ???