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

28th Dec 2017, 3:42 PM
Yololab
Yololab - avatar
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
28th Dec 2017, 3:47 PM
David Akhihiero
David Akhihiero - avatar
+ 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 ???
28th Dec 2017, 3:45 PM
Yololab
Yololab - avatar