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] _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor