python pass by value or reference code example
Example 1: python pass by reference
myList = ['foo', 'bar']
def modifyList(l):
l.append('qux')
l = ['spam', 'eggs']
l.append('lol')
modifiyList(myList)
print(myList)
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)
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)