Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: "Chained definition" of ints vs lists

Tags:

python

I just discovered in the definition of variables in Python. Namely:

a = b = 0
a = 1

gives me a=1 and b=0 or a and b are two independent variables.

But:

a = b = []
a.append(0)

gives me a = [0] and b = [0], or a and b are two references to the same object. This is confusing to me, how are these two cases different? Is it because int are primitive types or because lists are just pointers?

like image 288
Learning is a mess Avatar asked Apr 23 '15 14:04

Learning is a mess


1 Answers

a and b point to the same object always. But you cannot alter the integer, it is immutable.

In your first example, you rebound a to point to another object. You did not do that in the other example, you never assigned another object to a.

Instead, you asked the object a references to alter itself, to add another entry to that object. All other references to that same object (the list), will see these changes. That's because list objects are mutable.

A proper comparison would be to re-assign a to point to a new list object:

a = b = []
a = [0]

Now you rebound a and b is still referencing the first list object.

like image 165
Martijn Pieters Avatar answered Oct 08 '22 22:10

Martijn Pieters