[Tutor] Scope and values in a list

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 27 Dec 2000 02:09:40 +0100


Sometimes I over-explain the "everything is a reference" thing and it's
late at night now so I'm overdoing it more than usual I think, but maybe
it's helpful. I consider this the key point of Python and its worth
being hit with a hammer for a few times to make sure it's understood ;-).

On Tue, Dec 26, 2000 at 08:49:33AM -0800, Mallett, Roger wrote:
> Alright, being that 
> > When you do "myList = newList", 
> > that old list isn't changed at 
> > all, rather myList now refers to
> > a new list.
> 
> AND being that: "since everything in Python is a reference, and the variable
> doesn't hold any value but is a name for an object", 
> 
> then why does x display its newly assigned value (10...19) once the *for*
> loop has complete (see output below)?

Since 'x' is now a name for that new list. But the 'for' loop only looks
up the name 'x' once (when it starts), so it is using the old list.

> Seems that myList does indeed take on
> the new value, but that the "i" in the *for* loop is using a snapshot of the
> myList object to iterate (and not actually using myList).  Is that true?

Depends how you mean that. It's not making a copy of the list, or something
like that. The for loop looks up the reference at the beginning of the
loop; then it keeps the reference to the list and loops through it. It doesn't
care what happens to the name "myList" after it starts.


Let's show it step by step (arrows mean "refers to"):

> >>> x = range(10)

The situation is now:

   x     ------->     [List A, containing 0...9]
   
> >>> for i in x:

   x     ----+-->     [List A, containing 0...9]
   for loop -/
      
> ... 	x = range(10,20)

   for loop ----->    [List A, containing 0...9]
   x ------------>    [Some new list B, containing 10...19]
   
(the assignment makes x refer to something new, but nothing more; in
particular the for loop still uses the old reference)

(next loop through the for:)

   for loop ----->    [List A, containing 0...9]
                      [List B, 10...19, not used anymore, will be freed]
   x ------------>    [Some new list C, containing 10...19]

(etc)

> ... 	print i,
> ... 	
> 0 1 2 3 4 5 6 7 8 9
> >>> x

   x ----------->   [List K or so, the last one that was made, 10...19]
   (the rest have been freed because nothing referred to them anymore)
   
> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


Whatever. Time to sleep.

Remco Gerlich