Apr 5, 2018

python list vs tuple

t1 = [1,2,3,4]
t2 = t1
t2.append(5)
print 'T1: ' + str(t1)
print 'T2: ' + str(t2)

print '------------------'

t1 = (1,2,3,4)
t2 = t1
t2 = t1 + (5,)
print 'T1: ' + str(t1)
print 'T2: ' + str(t2)


Output:
T1: [1, 2, 3, 4, 5]
T2: [1, 2, 3, 4, 5]
------------------
T1: (1, 2, 3, 4)
T2: (1, 2, 3, 4, 5)


Reason:
Tuples are immutable and not supposed to be changed
Lists are mutable and are supposed to be changed


No comments:

Post a Comment