+ 1
Need help with List qn
list1=[1,2] list2=list1 list3=list2[:] print(list1) print(list2) print(list3) #all lists print [1,2] a=list2 is list1 b=list3 is list1 print(a,b) #prints true, false #why is b false?
4 Respostas
+ 1
the third expression uses slice notation.
A slice creates a whole new object - mostly just a part (slice) of the original, like [:2].
[:] is a shortcut for saying: Make a copy from this part of the list - this part being the whole thing. ;-)
Anyways, list3 is a copy, a twin, of list2, so 'is' turns out False.
list1 and list2 on the other hand, are only two different names for the very same thing.
Like you call your father 'father', but your grandfather calls your father 'son', although it's the same person.
+ 1
"is" returns True if and only if two objects have the same memory address.
List 1 and 2 are the same list, only with an other name.
List 3 is a new list, witchs holds copied items from list1, 2
0
You can check the memory address with
print(id(list1))
This must be the same for list1, 2
0
Thanks for responding so fast and making it easy to understand!