Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto do reference to ints by name in Python

I want to have a a reference that reads as "whatever variable of name 'x' is pointing to" with ints so that it behaves as:

>>> a = 1
>>> b = 2
>>> c = (a, b)
>>> c
(1, 2)
>>> a = 3
>>> c
(3, 2)

I know I could do something similar with lists by doing:

>>> a = [1]
>>> b = [2]
>>> c = (a, b)
>>> c
([1], [2])
>>> a[0] = 3
>>> c
([3], [2])

but this can be easily lost if one assigns a or b to something instead of their elements.

Is there a simple way to do this?

like image 383
unode Avatar asked Dec 28 '22 06:12

unode


1 Answers

No, there isn't a direct way to do this in Python. The reason is that both scalar values (numbers) and tuples are immutable. Once you have established a binding from a name to an immutable value (such as the name c with the tuple (1, 2)), nothing you do except reassigning c can change the value it's bound to.

Note that in your second example, although the tuple is itself immutable, it contains references to mutable values. So it appears as though the tuple changes, but the identity of the tuple remains constant and only the mutable parts are changing.

like image 136
Greg Hewgill Avatar answered Dec 30 '22 18:12

Greg Hewgill