I am starting out learning Python syntax and in the book that I am reading it is mentioned that objects are assigned by reference and not by value, i.e. foo1=4
Now foo2 and foo1 refer to the same object in memory and I even verified this by using the 'is' keyword that tests for reference equality. Now, if I increment foo1 and check for object equality using 'is' I am getting a 'False' value. Why is that? When I try to print out the value of foo2 it remains unchanged and when I print foo1's value the value has incremented. I did not understand the concept of assigning the objects reference if the value does not update itself in both the variables. Can anyone please explain this observation? Thank you!

Edited 1 Year Ago by anumash

AFAIK, there is no inplace augmented assignment operator for integers in python. It means that in

foo = 4
foo += 1

the second statement creates a new int object and assigns it to the name foo.

For user defined types, the python documentation recommends to define += as an inplace operation (method __iadd__()) if it is possible, but it is not enforced, and obviously, it cannot be done for immutable types such as int.

Edit: it works for lists (a mutable type)

>>> foo = [1, 2, 3]
>>> bar = foo
>>> foo += [4, 5]
>>> bar
[1, 2, 3, 4, 5]

It means that the first important type classification in python is mutable vs immutable.

Edited 1 Year Ago by Gribouillis

To further the foo_1 is not mutable (when it is changed it resides at a new memory address).

print "at memory address", id(foo_1)

foo_1 += 2
print "not mutable so new value=new address"
print id(foo_1)

print "\n lists are mutable (same memory address)"
foo_1 = [3]
print id(foo_1)
foo_1[0] += 2
print id(foo_1)

If you create a list or dictionary object in Python, you are really creating an instance of a class. Class instances are reference types. You can test that out on a class you write yourself.

This article has been dead for over six months. Start a new discussion instead.