Python works so that I can update a list
in place every time a function runs:
list_obj = list()
def increase_list_obj(list_obj, n):
list_obj.append(n)
print(list_obj)
for n in range(3):
increase_list_obj(list_obj, n)
print(list_obj)
OUTPUT:
[]
[0]
[0, 1]
[0, 1, 2]
Based on how the list
persists I would expect that I can also update an int
in place every time a function runs:
int_obj = 0
def increase_int_obj(int_obj):
int_obj += 1
print(int_obj)
for n in range(3):
increase_int_obj(int_obj)
print(int_obj)
OUTPUT:
0
0
0
0
EXPECTED:
0
1
2
3
Why does the int
update not work the same way as the list
update?
How are the persistence and scoping rules different for these two objects?
(I am NOT trying to suggest that the two should behave the same, I am curious about why they don't)
To preempt answers about how to update an int
: I realize you can update the int
value by just returning it from the function:
int_obj = 0
def increase_int_obj_v2(int_obj):
int_obj += 1
return int_obj
print(int_obj)
for n in range(3):
int_obj = increase_int_obj_v2(int_obj)
print(int_obj)
OUTPUT:
0
1
2
3
Thank you!