simple question re list iteration semantics
Wed Apr 22 04:56:03 CEST 2009
Esmail <ebonak at hotmail.com> 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.
> Would the 2nd one be considered more Pythonic? (It looks both
> clearer and cleaner to me).
Yes. 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.
More information about the Python-list