Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store reference to primitive type in Python?

Code:

>>> a = 1
>>> b = 2
>>> l = [a, b]
>>> l[1] = 4
>>> l
[1, 4]
>>> l[1]
4
>>> b
2

What I want to instead see happen is that when I set l[1] equal to 4, that the variable b is changed to 4.

I'm guessing that when dealing with primitives, they are copied by value, not by reference. Often I see people having problems with objects and needing to understand deep copies and such. I basically want the opposite. I want to be able to store a reference to the primitive in the list, then be able to assign new values to that variable either by using its actual variable name b or its reference in the list l[1].

Is this possible?

like image 753
fdmillion Avatar asked May 23 '13 01:05

fdmillion


2 Answers

There are no 'primitives' in Python. Everything is an object, even numbers. Numbers in Python are immutable objects. So, to have a reference to a number such that 'changes' to the 'number' are 'seen' through multiple references, the reference must be through e.g. a single element list or an object with one property.

(This works because lists and objects are mutable and a change to what number they hold is seen through all references to it)

e.g.

>>> a = [1]
>>> b = a
>>> a
[1]
>>> b
[1]
>>> a[0] = 2
>>> a
[2]
>>> b
[2]
like image 83
Patashu Avatar answered Sep 28 '22 00:09

Patashu


You can't really do that in Python, but you can come close by making the variables a and b refer to mutable container objects instead of immutable numbers:

>>> a = [1]
>>> b = [2]
>>> lst = [a, b]
>>> lst
[[1], [2]]
>>> lst[1][0] = 4  # changes contents of second mutable container in lst
>>> lst
[[1], [4]]
>>> a
[1]
>>> b
[4]
like image 25
martineau Avatar answered Sep 28 '22 00:09

martineau