Monday 17 January 2011

Python assignment: by value or by reference?

I was really confused some time ago regarding the assignment method used by Python. Ok, let's take it one step at a time.

Assignment in Python is done by reference, not by value

This is correct, but let's take the following example:

>>> a = 1
>>> b = a
>>> a = 2
>>> b
1
>>>

The expected result would be 2, not 1. Let's take the following example to make things even more strange:

>>> list1 = [1, 2, 3]
>>> list2 = list1
>>> list2[0] = 100
>>> list1
[100, 2, 3]
>>>

Well, which one is it? The answer is: integers are immutable, which means we can't change them. Let's analyze the first example: a = 1. Two things are being created: the object a and the value 1. Some a points to 1. Next, b = a. Object b is created and b points to the value of a.

Now, let's shake things up: a = 2. You'd think that the innitial value that a was pointing too will change. But, as integers are immutable, that doesn't happen. Instead, a new integer object is created. So now, a is now pointing at the new integer object specified, as for b, it points at at the same old object that a used to be pointing at.

No comments:

Post a Comment