Home » Odeon Blogs » Bogdan, Methodical Coder »

Python assignment: by value or by reference?

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:

  1. >>> a = 1
  2. >>> b = a
  3. >>> a = 2
  4. >>> b
  5. 1
  6. >>>

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

  1. >>> list1 = [1, 2, 3]
  2. >>> list2 = list1
  3. >>> list2[0] = 100
  4. >>> list1
  5. [100, 2, 3]
  6. >>>

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.


Category: Python



Leave a Comment :

(required)


(required)




(required)




(required)






Leave a Comment


Page generated in: 0.14s