Understanding While Loop Execution

Tim Roberts timr at probo.com
Tue Feb 19 01:21:04 EST 2008


Gary Herron <gherron at islandtraining.com> wrote:
>
>So in the following code, the list named full does not have 3 copies of 
>sub in it, but rather it has 3 *references* to the single list named 
>sub.

Since we are being picky here, it's more accurate to say that the list
"full" contains 3 references to the list that is also referenced by the
name "sub".  I've found that it is more useful to think of Python objects
(like lists) as anonymous things living out in object memory (which is, no
doubt, a happy place), and all of the names in the program just refer to
those anonymous things.

>Any changes to the list named sub will be reflected anywhere that 
>list is referred to.

And vice versa.  "sub" is a reference to the list, exactly like "full[0]".
No difference.

> >>> sub = [1,2,3]
> >>> full = [sub,sub,sub]
> >>> full
>[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
> >>> sub[0] = 123
> >>> full
>[[123, 2, 3], [123, 2, 3], [123, 2, 3]]

And:

>>> full[0][2] = 99
>>> sub
[123, 2, 99]
>>> full
[[123, 2, 99], [123, 2, 99], [123, 2, 99]]
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list