Is 'everything' a refrence or isn't it?

Simon Brunning simon at brunningonline.net
Wed Jan 4 14:26:02 EST 2006


On 4 Jan 2006 10:54:17 -0800, KraftDiner <bobrien18 at yahoo.com> wrote:
> I was under the assumption that everything in python was a refrence...
(snip)
> Have I misunderstood something?

Yup. The concept if a reference is, I find, sometimes an unhelpful one
in Python. Reset your brain -
<http://effbot.org/zone/python-objects.htm>.

Armed with that, let's go through your code:

> lst = [1,2,3]

Here, you've created a list object, and bound it to the name "lst".
The list contains references to three integer objects. (OK I said
"reference" there didn't I? Well, I only said that it's *sometimes* an
unhelpful concept. ;-) I do tend to think of collections as refering
to objects. It's when dealing with you might call variables that it's
misleading - there it's better to think of names, objects, and
bindings.)

> for i in lst:

Here, you are iterating through the list that's currently bount to the
name "lst". You are binding each element of the list in turn to the
name "i".

>    if i==2:

If the object to which the name "i" is currently bound compares equal to 2...

>       i = 4

Rebind the name "i" to the integer object 4. Note that this has no
effect on the object that used to be bound to "i" at this point, nor
any effect on the list object.

> print lst

Print your old list.

Clear now?

--
Cheers,
Simon B,
simon at brunningonline.net,
http://www.brunningonline.net/simon/blog/



More information about the Python-list mailing list