Scenario 1 : Mutable object like list
def a(l):
l[0] = 1
print("\nValue of l = {0} in a()".format(l))
def b(l):
l = l + [9]
print("\nValue of l = {0} in b()".format(l))
l = [0]
a(l)
print("\nValue of l = {0} after executing a()".format(l))
b(l)
print("\nValue of l = {0} after executing b()".format(l))
Output
Value of l = [1] in a()
Value of l = [1] after executing a()
Value of l = [1, 9] in b()
Value of l = [1] after executing b()
Questions
- In the context of mutable objects, why is the modification done to l in b() not visible in global scope whereas it happens for a()?
Scenario 2 : Immutable object like integer
def a(l):
l = 1
print("\nValue of l = {0} in a()".format(l))
def b(l):
l = l + 9
print("\nValue of l = {0} in b()".format(l))
l = 0
a(l)
print("\nValue of l = {0} after executing a()".format(l))
b(l)
print("\nValue of l = {0} after executing b()".format(l))
Output
Value of l = 1 in a()
Value of l = 0 after executing a()
Value of l = 9 in b()
Value of l = 0 after executing b()
Questions
- In the context of immutable objects, why is the modification done to l in both a() and b() not visible in the global scope?
I checked with many folks and they couldnt explain this. Can someone explain the fundamental concepts used in this example?