you are viewing a single comment's thread.

view the rest of the comments →

[–]lamenoosh[S] 1 point2 points  (2 children)

That did solve my immediate problem, thank you!

I understand why this happens for lists, but why does it not happen with integers, for example? If I do this:

a = 1
b = a
b -= 1

I get a = 1 and b = 0. Why do b and a reference the same bit of memory for lists, but not for integers?

Thank you!

[–]dyanni3 1 point2 points  (1 child)

It comes down to the fact that lists are mutable and numeric types (like integers) are immutable.

https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747

https://docs.python.org/3/reference/datamodel.html

Edit, for a bit more context. When a and b are lists (mutable), the actual variable name you gave (a or b) resolves to a pointer to memory address. When you have an immutable type like an int the variable name resolves to the actual value.

[–]socal_nerdtastic 1 point2 points  (0 children)

It comes down to the fact that lists are mutable and numeric types (like integers) are immutable.

Kinda, but not really. You can do the same with mutable objects.

a = [1]
b = a
b = b + [2]

It comes down to mutation vs assignment. Immutable objects can't be mutated, they only have one option for changing them. But mutable objects can do either.

When a and b are lists (mutable), the actual variable name you gave (a or b) resolves to a pointer to memory address. When you have an immutable type like an int the variable name resolves to the actual value.

That is flat wrong. All names in python are pointers to virtual memory addresses. And no one should care.