variable in Python

Steve Holden sholden at holdenweb.com
Thu Apr 17 07:53:57 EDT 2003


"Salvatore" <artyprog at wanadoo.fr> wrote ...
> Hello,
>
> I have a little doubt concerning variables.
> When one declare x = 3
> does x contains the value 3 or
> does x acts like pointer in C ?
>

Salvatore:

All Python variables are references to the data values that have been
assigned to them - as are list and dictionary elements. This can lead to
surprises for beginners, who don't understand why

>>> lst1 = [1, 2, 3]
>>> lst2 = lst1
>>> lst2[2] = "bam!"

leads to the lst1 variable showing the value [1, 2, "bam!"]. The answer, of
course, is that the third assignment changes the last element of the list
that is referred to by both variables, lst1 and lst2.

Many Python authors prefer to talk about "binding" nowadays, since
"assignment" implies to users of other languages that a value is being
placed into the variable. In Python, however, this isn't the case. Data
values are created in memory allocated from a heap, and this memory is only
reclaimed when no references to the data vablue remain. Once the data value
is created, variables reference it.

In  the CPython implementation each reference to a value increments its
reference count, and deletion of a reference decrements that count. Certain
"cyclic" structures, being self-referential, would never be reclaimed, and
so recent versions of CPython have a garbage collection algorithm that can
detect otherwise-unreferenced cyclic structures.

The JPython implementation, which compiles Python into Java bytecodes, does
not use reference counting at all and relies on Java's garbage colection
scheme to reclaim unused memory.

regards
--
Steve Holden                                  http://www.holdenweb.com/
How lucky am I?      http://www.google.com/search?q=Steve+Holden&btnI=1
Python Web Programming                 http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list