rgv
rgv

Reputation: 91

Why both the lists gets changed wheres only 1 tuple gets changed

Consider the following python code involving lists and tuples:

l1=[1,2,3,4]
l2=l1
l2.append(5)
print('l1:',l1)
print('l2:',l2)
t1=(1,2,3,4)
t2=t1
t2+=(5,)
print('t1:',t1)
print('t2:',t2)

When we run this code then output is:

l1:[1,2,3,4,5]
l2:[1,2,3,4,5]
t1:(1,2,3,4)
t2:(1,2,3,4,5)

Why does it happens that, in case of list, both the list, l1 and l2 gets changes whereas in case of tuple only 1 tuple, t2 gets changed?

Upvotes: 1

Views: 92

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 11992

Tuples are immutable and lists are mutable. this means you can change the value of a list but not the value of a tuple. When you do t2 += (5,) the value in t2 is copied and concat with your tuple of 5 this creates a new tuple which is then stored in t2. so t1 and t2 now dont point to the same object. You can see this by looking at the id of the obejcts

l1=[1,2,3,4]
l2=l1 #this points l2 to the same list as l1
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
l2.append(5) # this changes the list that l1 and l2 points to
print('l1:',l1, "ID:", id(l1))
print('l2:',l2, "ID:", id(l2))
t1=(1,2,3,4)
t2=t1 # this points t2 to the same tuple as t1
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))
t2+=(5,) # This creates a new tuple and points t2 to it. t1 still points to the old tuple
print('t1:',t1, "ID:", id(t1))
print('t2:',t2, "ID:", id(t2))

OUTPUT

C:\Users\cd00119621\.virtualenvs\stackoverflow-yoix_gHB\Scripts\python.exe C:\Users\cd00119621\PycharmProjects\stackoverflow\stackoverflow.py
l1: [1, 2, 3, 4] ID: 56608872
l2: [1, 2, 3, 4] ID: 56608872
l1: [1, 2, 3, 4, 5] ID: 56608872
l2: [1, 2, 3, 4, 5] ID: 56608872
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4) ID: 56771760
t1: (1, 2, 3, 4) ID: 56771760
t2: (1, 2, 3, 4, 5) ID: 25919192

Process finished with exit code 0

Upvotes: 2

Related Questions