[Tutor] range/for list change behavior

Steve Willoughby steve at alchemy.com
Tue Sep 30 05:17:52 CEST 2008


Don Parris wrote:
> Hi all,
> 
> After a rather long (and unfortunate) break from tinkering with Python, 
> I am back at it.  I am working through the book Learning Python (based 
> on 2.2/2.3 - I use 2.5), and in the chapter on while/for loops, ran 
> across the following example:
> 
>  >>> L = [1, 2, 3, 4, 5]
>  >>> for i in range(len(L)):
> ...     L[1] += 1                         # this is a typo I made - 
> should have been L[i], not L[1].
> ...
>  >>> L
> [1, 7, 3, 4, 5]
> 
> I did correct my typo, but what I do not understand is how range arrived 
> at a '7', where the '2' should be.  My best guess is that L[1] is 
> treated as the index of the value '2'.  I hope that learning how my 

You are correct.  In the expression L[n], you are referring to the nth
element in the list L (where n starts at 0).  So L[1] is the element
which starts off with the value 2 in your example.

When you execute:

	for i in range(len(L)):
		L[1] += 1

that will increment element #1 once each time through the loop,
giving you the result [1, 7, 3, 4, 5]

If you correct your loop to read as:

	for i in range(len(L)):
		L[i] += 1

You'll get [2, 3, 4, 5, 6] as the result.  i will iterate over
the range from 0 to len(L)-1, or [0,1,2,3,4] and for each of those
numbers increment the corresponding element of L.


> error affected the result will help me grasp the concept a little better.
> 
> Thanks!
> Don
> -- 
> D.C. Parris
> Minister, Journalist, Free Software Advocate
> https://www.xing.com/profile/Don_Parris
> http://www.linkedin.com/in/dcparris
> sip:dcparris at ekiga.net <mailto:sip%3Adcparris at ekiga.net>
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list