[Tutor] List index usage: is there a more pythonesque way?

ALAN GAULD alan.gauld at btinternet.com
Mon Apr 19 09:18:49 CEST 2010


> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Technically its still one key but enumerate returns a tuple 
of index and value and we use tuple unpacking to assign 
the values to the loop variables. That is we could write it like:

for tup in enumerate(sequence):
     index = tup[0]
     value = tup[1]
     # process stufff here
OR:
for tup in enumerate(sequence):
     index,value  = tup
     # process stufff here

Which becomes
for index, value in enumerate(sequence):
     # process stufff here

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100419/145ae46b/attachment-0001.html>


More information about the Tutor mailing list