simple question re list iteration semantics

Dave Angel davea at ieee.org
Tue Apr 21 22:16:05 EDT 2009


Esmail wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hello all,
>
> I have a simple question regarding semantics.
>
> Given a list 'li', I can always do this to iterate through all items in
> order:
>
> for i in range(0, len(li)):
>     print li[i]
>
> Will this always be equivalent to
>
>
> for i in li:
>     print i
>
> I assume it is, and the order will always be the same, or am I mistaken?
>
> Would the 2nd one be considered more Pythonic? (It looks both
> clearer and cleaner to me).
>
> Thanks.
>
> Esmail
>
>
> </div>
>
The second one will be equivalent if li is really a list.  With a few 
differences, such as:
    1) it's faster
    2) it doesn't create an extra temporary list (although on python 
3.0, neither will the first one)
    3) the subsequent value of i is the last element of the list, rather 
than the last index in the list
    4) it'll work even if li is later changed to a generator
    5) it'll do something useful even if the li is changed to a 
dictionary or a set, although order isn't guaranteed there
    6) it'll behave differently if the list is changed during the loop

The second one is definitely more pythonic.




More information about the Python-list mailing list