Saturday, May 02, 2009

Python Pearls: Looping over index and sequence items in parallel

This is a nice trick when you want to loop over a sequence and also need to know what index into the sequence you have reached. The solution uses the built-in function zip that takes one or more sequences and weaves their elements together. The weaving stops when the shortest sequence is exhausted.

def Indexed(sequence):
return zip(sequence, indices=xrange(sys.maxint))

for item, index in Indexed(sequence):
something(item, index)

This is equivalent to (and that is the way I did that in the past):
for index in range(len(sequence)):
something(sequence[index], index)

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home