XOR Media

Coding, Operations, Etc.

Simple Python Iterator to Walk a List in Pairs

Posted on Mon 14 May 2012 by

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.

In code, tagged: python, coding, and examples.

About the Author

Ross McFarland Ross McFarland | | |

Ross is a 17 year veteran of the software industry with experience spanning low-level signal processing, web and mobile user interfaces, high-scale distributed web services, infrastructure, and networking. He has made extensive contributions to open source highlighted by his time as a primary maintainer of Gtk2-Perl and author of requests-futures and python-asynchttp libraries. (more)