why in the following case list2 is not [3,5]
?
>>>list1=[3,5]
>>>list2=list1
>>>list1[0]=2
>>>list1
[2,5]
>>>list2
[2,5]
but when I try here it is[3,5]:
>>>list1=[3,5]
>>>list2=list1
>>>list1=[3,5,7]
>>>list2
[3,5]
why in the following case list2 is not [3,5]
?
>>>list1=[3,5]
>>>list2=list1
>>>list1[0]=2
>>>list1
[2,5]
>>>list2
[2,5]
but when I try here it is[3,5]:
>>>list1=[3,5]
>>>list2=list1
>>>list1=[3,5,7]
>>>list2
[3,5]
Python variable names point at objects.
list2=list1
causes list2
to point at the same object as list1
.
list1[0]=2
modifies the list1
object in-place, so list2
is affected as well.
In contrast,
list1=[3,5,7]
causes list1
to point at a different list. So list2
and list1
no longer point at the same object. Thus list2
remains equal to [3, 5]
in the second situation.
See Mark Ransom's answer for a nice explanation of Python's variable / object / assignment model.
The pictures above were generated by the Online Python Tutor visualizer. You can use it to see how the assignments change the variable's values step-by-step.
In the first example, you change the object being pointed to by list1
and list2
"in place". In the second, you assign list1
to a completely new object, leaving only list2
pointing to the original object. Use id()
or is
to see when two names point to the same object:
>>> list1=[3,5]
>>> list2=list1
>>> list1[0]=2
>>> list1 is list2
True
versus
>>> list1=[3,5]
>>> list2=list1
>>> list1=[3,5,7]
>>> list1 is list2
False