List Mutability:
- List is Mutable
- Mutable object can be modified.
- Address remains same after modification of Mutable object
a = [10, 20]
print("List is :",a)
print("Address :",id(a))
a.append(30)
print("After append, List is :",a)
print("Address :",id(a))
a.pop()
print("After pop, List is :",a)
print("Address :",id(a))
- In Python, Strings, Integers, Floats all elements are Immutable objects.
- Immutable object get another location when we modify.
a = [10,20]
print("List is :", a)
print("Address of a :",id(a))
print("a[0] :", a[0])
print("a[0] address :", id(a[0]))
a[0]=a[0]+5
print("List is :", a)
print("Address of a :",id(a))
print("a[0] :", a[0])
print("a[0] address :", id(a[0]))
Output:
List is : [10, 20]
Address of a : 54494008
a[0] : 10
a[0] address : 1647965392
List is : [15, 20]
Address of a : 54494008
a[0] : 15
a[0] address : 1647965472
- Immutable objects cannot be duplicated.
- Contents with same values will share the memory.
a = [10, 20, 10]
print("List is :", a)
print("id(a[0]) :",id(a[0]))
print("id(a[1]) :",id(a[1]))
print("id(a[2]) :",id(a[2]))
a[2]=a[2]+10
print("id(a[1]) :",a[2])
print("id(a[2]) :",id(a[2]))
Output:
List is : [10, 20, 10]
id(a[0]) : 1647965392
id(a[1]) : 1647965552
id(a[2]) : 1647965392
id(a[1]) : 20
id(a[2]) : 1647965552
- List is Mutable – We can modify the List
- List elements either Mutable or Immutable
LIST = [10, “abc” , [20,30,40] , 23.45]