I wrote the following code to check if integers are passed by value or reference.
foo = 1
def f(bar):
print id(foo) == id(bar)
bar += 1
print foo, b
In Python 2, the current implementation keeps an array of integer objects for all integers between -5 and 256. So if you assign a variable as var1 = 1
and some other variable as var2 = 1
, they are both pointing to the same object.
Python "variables" are labels that point to objects, rather than containers that can be filled with data, and thus on reassignment, your label is pointing to a new object (rather than the original object containing the new data). See Stack Overflow question Python identity: Multiple personality disorder, need code shrink.
Coming to your code, I have introduced a couple more print statements, which will display that the variables are being passed by value
foo = 1
def f(bar):
print id(foo) == id(bar)
print id(1), id(foo), id(bar) #All three are same
print foo, bar
bar += 1
print id(bar), id(2)
print foo, bar
f(foo)