simple question re list iteration semantics

E

Esmail

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

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
 
S

Steven D'Aprano

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

Will this always be equivalent to

for i in li:
print i


For lists, yes, that will always be equivalent, and the second one is
considered more Pythonic.
 
P

Paul Rubin

Esmail said:
for i in range(0, len(li)):
print li

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.
 
E

Esmail

Paul said:
Esmail said:
for i in range(0, len(li)):
print li

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!
 
E

Esmail

Paul said:
Esmail said:
for i in range(0, len(li)):
print li

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top