+ 1

I dont understand why list2 was updated automatically

list1 = [1,2,3,4]; list2 = list1; list1.append(5); print(list1); print(list2); the result is [1 2 3 4 5] for both lists I thought only list1 would get the new element in the end. why did list2 get updated if only list1 got the last element appended? if the definition of list2 came after the append command, that would be clear to me. but that's not the case here.

16th Jan 2018, 12:39 PM
Robson Marini
Robson Marini - avatar
2 Respuestas
+ 1
When you write list2=list1, they point to one address of memory. Command 'list2 is list1' will also return true. If you want the same list but different object, create a new empty list and add there all objects from the first one.
16th Jan 2018, 1:15 PM
Petr Leliaev
Petr Leliaev - avatar
+ 1
thanks man. i just checked what you said. now i understand. however it is funny, cos if i define a new list list3 = [1,2 ,3 , 4] and type list1 is list3, it returns false. if i do the same for numbers. it works. a = [1, 2, 3, 4] b = a c = [1, 2, 3, 4] print(a is b) print(a is c) x = 2 y = x w = 2 print(x is y) print(x is w) the result is: true false true true funny how it answers differently for lists and numbers.
16th Jan 2018, 1:40 PM
Robson Marini
Robson Marini - avatar