Immutability:
- List is Mutable – can modify
- Modification methods are present in List object.
- List elements also can modify.
>>> a = [10,20]
>>> a.append(30)
>>> print(a)
[10, 20, 30]
>>> a[1]=a[1]+5
>>> print(a)
[10, 25, 30]
- Tuple is Immutable – Constant object.
- Modification methods are not present in tuple object.
- Only 2 methods present in Tuple object called index() and count()
>>> t = (10,20,30,20)
>>> t.count(2)
0
>>> t.count(20)
2
>>> t.index(20)
1
We cannot modify the elements of Tuple.
>>> t = (10,20,30)
>>> t[0]
10
>>> t[0] = t[0]+5
TypeError: 'tuple' object does not support item assignment
- Tuple is allowed to store both Mutable and Immutable objects.
- Hence we can store list inside tuple.
- List is Mutable object
>>> t = (10,20,[30,40,50])
>>> print(t)
(10, 20, [30, 40, 50])
We can modify the List which is inside the tuple.
>>> t = (10,20,[30,40,50])
>>> print(t)
(10, 20, [30, 40, 50])
>>> t = (10,20,[30,40,50])
>>> t[2]
[30, 40, 50]
>>> t[2].pop() #removes last element
50
>>> print(t)
(10, 20, [30, 40])
>>> t[2]
[30, 40]
>>> t[2].reverse()
>>> print(t)
(10, 20, [40, 30])
>>> t[2][0]
40
>>> t[2][0]=t[2][0]+5
>>> print(t)
(10, 20, [45, 30])
- List is Mutable – Not constant
- List is allowed to store both Mutable and Immutable objects.
- Tuple is Immutable – Constant
- Tuple elements can store both Mutable and Immutable Objects.