A certainl part of an if() structure never gets executed.

Michael Torrie torriem at gmail.com
Sat Jun 15 13:45:08 EDT 2013


On 06/15/2013 10:18 AM, Nick the Gr33k wrote:
> a and b you say are names, which still are memory chunks

Yes no matter how you look at it, a dictionary of names and objects is
memory and "variables" in that sense.  But at a higher level, we can
consider the differences with how a language like C defines variables.

> In both situations we still have 2 memory units holding values, so hows 
> that different?

Perhaps one could think of python names as more like pointers or
references in C. But python references are counted and garbage-collected
(more like a C++ reference-counting pointer type).

For example, a = 4 makes the name "a" be a reference to the object
int(4), which will never ever change in its lifetime (indeed it wouldn't
make sense for the integer 4 to change otherwise it wouldn't be a 4).
Thus a = a + 1 creates a new object that represents the integer value of
4 + 1, and throws the old object away.

>>> a = 5
>>> id(a)
2857664
>>> a = a + 1
>>> id (a)
2857680
>>>

Note that the identity (object) of a has changed.  If a were a variable
in the same sense as C, the identity of a would not change.

A mutable object like a list acts more like a variable in some ways:
>>> b = []
>>> id(b)
3076765292
>>> b.append(3)
>>> id(b)
3076765292

In many cases the distinction is little more than intellectual for all
intents and purposes, though it some cases the idea is very powerful.

But there a couple of cases where the difference between a variable and
a name referencing an object does bite people in Python:
http://effbot.org/zone/default-values.htm
http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference



More information about the Python-list mailing list