DEV Community

loading...

Python: Pass by Sharing

Swastik Baranwal
A noob
Updated on ・2 min read

In Python there is only pass by sharing or pass by object which means that according on the object it will change its value i.e. depending if it is mutable or not but you will not be able to change the type of object completely.

When people say that python has both
no pass by value and no pass by reference when they are teaching because they want beginners to know this as it is very crucial for understanding the concepts of programming. Most languages don't have pass by object as far I know.

def change_list(change):
    change += [2, 5, 7, 56, 79]

def change_dict(dict, value):
    dict[value] = 12

def change_obj(obj):
   obj = tuple(obj)

These are functions for various objects we are gonna test on.

List

int_list = [2, 5, 45, 676, 56]
change_list(int_list)
print(int_list)

The output of the code will be [2, 5, 45, 676, 56, 2, 5, 7, 56, 79] because the list is mutable and it has += operator support.

If change_obj() function is used for int_list; int_list will remain a list as the type is changed locally and not globally.

Tuple

int_tuple = (23, 56, 54)
change_list(int_tuple)
print(int_tuple)

This will not work as tuples don't support += operator and they are immutable.

Dictionary

age = {'Sam' : 12, 'Tom' : 15, } 
change_dict(age, 'Jack')
print(age)

The output of the code will be {'Sam' : 12, 'Tom' : 15, Jack : 12} as dict is mutable.

String, Int and Floats

Strings, Int and Floats are immutable by default so there's is no use of elaborating this and just like stated above type of object cannot be changed.

Further Reading

Call By Objects by effbot.org

Python Objects by effbot.org

If there is any confusion or anything misleading then please don't forget to comment.

Discussion (0)