0

I am studying Wes McKinney's 'Python for data analysis'. At some point he says: "When assigning a variable (or name) in Python, you are creating a reference to the object on the righthand side of the equals sign. In practical terms, consider a list of integers:

In [8]: a = [1, 2, 3]
In [9]: b = a
In [11]: a.append(4)
In [12]: b

output will be:

Out[12]: [1, 2, 3, 4]

He reasons as such: "In some languages, the assignment of b will cause the data [1, 2, 3] to be copied. In Python, a and b actually now refer to the same object, the original list"

My question is that why the same thing does not occur in the case below:

In [8]: a = 5
In [9]: b = a
In [11]: a +=1
In [12]: b

Where I still get

Out[12]: 5

for b?

reza
  • 1
  • 1
    Everything you need to know: [Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015](https://www.youtube.com/watch?v=_AEJHKGk9ns) – Mike Scotty May 03 '22 at 14:26

1 Answers1

0

In the first case, you're creating a list and both a and b are pointing at this list. When you're changing the list, then both variables are pointers at the list including its changes.

But if you increase the value of a variable that points at an integer. 5 is still 5, you're not changing the integer. You're changing which object the variable a is pointing to. So a is now pointing at the value 6, while b is still pointing at 5. You're not changing the thing that a is pointing to, you're changing WHAT a is pointing to. b doesn't care about that.

LukasNeugebauer
  • 1,331
  • 7
  • 10
  • Thanks Lukas. However, the question still remains for me: why in the case of integer, the same reasoning as for the list is not applicable: When I add 1 to integer a, why does python change the object to which a and b refer to? the logic Python used in the case of lists? – reza May 03 '22 at 14:38
  • Because you can change a list, but not an integer. Integers from -5 to 255 are already in memory when you start python. That's because they are the most frequently used. If you increase `a` by 1, then `a` is no longer pointing to the `int` value 5, but to 6. But `b` is still pointing to the 5, because that's unchanged. – LukasNeugebauer May 03 '22 at 14:40
  • If you want, have a look at the "identity vs. equality" part of this notebook: https://github.com/LukasNeugebauer/Python_Workshop/blob/master/notebooks/04_basic_syntax.ipynb – LukasNeugebauer May 03 '22 at 14:43
  • In many languages, there are two types of variables: variables that are values (such as integers) and variables that are pointers to a data structure else (such as arrays and objects). In Python, all variables are pointers, so a statement like `a += 1` can't just modify the value stored in `a`; the value isn't stored in `a` to begin with, and if you changed it, *all variables that contained the value `1` would be changed.* So integers are designated immutable, and "changing their value" necessarily involves changing what `a` points to. – kindall May 03 '22 at 14:59