[Tutor] For Loop question

Mark Tolonen metolone+gmane at gmail.com
Fri Jun 27 08:45:34 CEST 2008


"Lie Ryan" <lie.1296 at gmail.com> wrote in message 
news:1214493328.6462.11.camel at lieryan-laptop...
> On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores <rdm at rcblue.com> 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




More information about the Tutor mailing list