"Lie Ryan" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
 Hi I'm learning FOR loop now, very easy too learn. But I get confused
to understand this code :

myList = [1,2,3,4]
for index in range(len(myList)):
    myList[index] += 1
print myList

And the response is:
[2, 3, 4, 5]

Can you explain me as a newbie, how that code works ??


Ahhh... don't write it like that. It is not a pythonic way to use loop.

For-loop in python can loop over sequence (list, tuple, dictionary,
iterable, etc) directly (in Visual Basic, like For...Each loop), you
very rarely would need to use range/xrange for the iterator, and you
should never use len() to pass to range.

The loop would be much more simpler, and understandable this way:

myList = [1, 2, 3, 4]
outList = []
for x in myList:
   outList.append(x + 1)
print outList

or in a more elegant way, using list comprehension:

myList = [1, 2, 3, 4]
print [(x + 1) for x in myList]


The above solutions create new lists. If a functional requirement is to modify the list in place, then the original is fine (on Python 2.6 and later) or should use xrange instead of range (on Python 2.5 or earlier, especially for large lists).

Another option is:

myList = [1,2,3,4]
for index,value in enumerate(myList):
   myList[index] = value + 1

-Mark


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to