PASS BY OBJECT REFERENCE FOR MUTABLE DATA TYPES

leoumesh(72)
Published in
GEMS
Words
87
Reading
1 min
Listen
Play
6y

In the last type we see Pass by Object Reference for immutable data type in python and in this we would do the same for mutable data types which are usually dictionary, list, tuple or set. Whenever you try to update these data types, a new object of these data types are not created in the memory and the value gets updated in the same memory address. This is because these data types are modifiable. Here's thee program demonstrating this concept.

def update(list):
    
    print("List before updating any value: ",list)
    print("Memory address of list before updating any value: ",id(list))
    list.append("Cuba")
    print("List after updating the value: ",list)
    print("Memory address of list after updating the value: ",id(list))
    
list=["Brazil","Finland","Maldives","Rwanda"]  
print("List before calling the function: ",list)
print("Memory address of list before the calling function: ", id(list))

update(list)
print("List after calling the function: ",list)
print("Memory address of list after calling the function: ", id(list))

You can see the output as:

Screenshot_3.png

PASS BY OBJECT REFERENCE FOR MUTABLE DATA TYPES | Ecency