XOR Media

Simple Python Iterator to Walk a List in Pairs

I’ve run in to a couple situations where I’ve wanted to iterate over a list in pairs lately and decided to create a simple iterator to clean up the code a bit.

In the following code I have a list of dictionaries that I’m going to convert in to a linked-list of sorts. I’ll grant you this doesn’t make a lot of sense in the trivial contrived case, but in my work I’ve encountered it as part of converting some legacy XML data to a newer and easier to work with JSON.

elements = ({'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': '4'})

for i, element in enumerate(elements[:-1]):
    element['next'] = elements[i + 1]['id']

Compare that to the following code.

for element, next in iterate_pairs(elements):
    element['next'] = next['id']

The iterate_pairs helper is pretty straightforward. It makes use of the yield_statement, which may take a bit of reading to grok if it’s not familiar to you. The function iterate_pairs is implemented as follows.

def iterate_pairs(a):
    for i in xrange(len(a) - 1):
        yield (a[i], a[i + 1])

It for-each’s n - 1 and yields (if nothing else think of it as returning each time around) the i-th element and it’s next, i + 1. That’s it, we can use this helper just like enumerate, but instead of getting the index along with each element we’ll get the element and it’s next door neighbor.