1

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]
2rs2ts
  • 10,662
  • 10
  • 51
  • 95
user7777777
  • 219
  • 2
  • 10

2 Answers2

7

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.

enter image description here

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. enter image description here

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.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437