Spot any errors? let me know, but Unleash your pedant politely please.

Friday 22 May 2009

Python : Iterating Multiple Lists

I did this a few times...

for index in range(len(aList)):
    doSomethingWith(aList[index], blist[index])
    doSomethingElseWith(cList[index])

Or even...

for a in aList:
    doSomethingWith(a, blist[aList.index(a)])
    doSomethingElseWith(cList[aList.index(a)])

And at some point, it felt wrong. It felt, I have come to understand, unPythonic.
Google was my friend, although I didn't really look or read enough, and I ended up with something like this:

a=0
b=1
c=2
for abc in zip(a,b,c):
    doSomethingWith(abc[a], abc[b])
    doSomethingElseWith(abc[c])


And I was happy. But putting it in a few more places, it also felt like unPython. So I decided to take a better look (actually just a better more explicit simple search for exactly what I wanted), and found the Pythonic way...

for a,b,c in zip(aList,bList,cList):
    doSomethingWith(a.b)
    doSomethingElseWith(c)

Refactoring to use this idiom has been wonderful. Lines of code disappearing and the code becoming more readable too. Marvellous !

(I think I found my answer at testing reflections

No comments:

Post a Comment