call by reference python code example

Example 1: python send object reference to another function and edit property

class Test:
  a = 1

def f(obj):
  obj.a = 10

t = Test()
f(t)

# t.a should be 10

Example 2: Is Python call by reference or call by value

If the object is mutable, the object will change.

eg:
  def my_func(my_list):
    my_list.append(5)
    print("List printed inside the function: ",my_list)
    
numberlist = [1,2,3]
my_func(numberlist)
# numberlist here changed since list is mutable in python 

If the object is immutable (like a string!), 
then a new object is formed, only to live within the function scope.

eg:
  def change_fruits(fruit):
    fruit='apple'
    
myfruit = 'banana'
change_fruits(myfruit)
# myfruit does not change since string is immutable in python