simple question re list iteration semantics

Esmail ebonak at
Wed Apr 22 05:11:56 CEST 2009

Paul Rubin wrote:
> Esmail <ebonak at> writes:
>> for i in range(0, len(li)):
>>      print li[i]
>> Will this always be equivalent to
>> for i in li:
>>      print i
> Not the same--after the exit of the first loop, 'i' is the length of
> the list.  After the exit of the second loop, 'i' is the last element.

Yes, agreed.

>  If you want to have the numeric index available in the loop, use:
>   for i,x in enumerate(li):
>      ...
> then i is the index and x is the element.

ah .. very nice, I didn't know this -- thanks!

More information about the Python-list mailing list