python pass by value or reference code example

Example 1: python pass by reference

# objects are passed by reference, but
# its references are passed by value

myList = ['foo', 'bar']

def modifyList(l):
  l.append('qux') # modifies the reference
  l = ['spam', 'eggs'] # replaces the reference
  l.append('lol') # modifies the new reference

modifiyList(myList)

print(myList) # ['foo', 'bar', 'qux']

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