Binding a variable?

David Wahler dwahler at gmail.com
Fri Oct 21 19:47:57 CEST 2005


Paul Dale wrote:
> Hi everyone,
>
> Is it possible to bind a list member or variable to a variable such that
>
> temp = 5
>
> list = [ temp ]
>
> temp == 6
>
> list
>
> would show
>
> list = [ 6 ]
>
> Thanks in advance?
>
> Paul

Python doesn't have "variables" -- a statement like "temp = 5" just
binds the name "temp" to an int object with value 5. When you say "list
= [temp]", that's putting the int object into the list; the name "temp"
is just a label for it, not a variable or container of any kind. Since
int objects are immutable, you can only change the value by assigning a
new object in its place.

That said, you can accomplish something like this by creating a new
class:

-----------------------------------
class MyInt:
    pass

>>> temp = MyInt()
>>> temp.i = 5
>>> list = [temp]
>>> temp.i = 6
>>> print list[0].i
6
-----------------------------------

Once your object is mutable, any changes to it will be reflected
anywhere there is a reference to it.

-- David




More information about the Python-list mailing list