Wednesday, 28 January 2009

Lock-step iteration in Python

Lock-step iteration

Parallel or lock-step iteration between 2 or more lists can be achieved using zip function. e.g.

import sys
spaghetti = [ 1,2,5,3 ] meatballs = [ 2,3,4,5 ] mozarella = [ 3,4,5,6 ]

def main(argv):
for t in zip(spaghetti, meatballs, mozarella): print t

main(sys.argv)


The enumerate method on Lists

a=['apple'. 'orange']
for i,v in enumerate(a):
print i, v

Iterating a List in Reverse

for i in reversed(a):
print i

reversed(a) returns a listreverseiterator object. This brings us to the following question.

How does iteration work in Python?

The for statement calls the iter() method on the container object. The iter() method returns an iterator object that defines the next() method which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the loop to terminate.

e.g. r = reversed(a); r.next()

No comments: