Although I've been working in Python for a long time, every once in a while I come across a chunk of code that makes me stop and think, and admire its elegance and Pythonic nature. Raymond Hettinger's recipe for merging multiple sorted iterators is one of those pieces of code. It's only 29 lines including the supporting stuff, but it opened my eyes in these ways:
- It works with iterators in unusual ways, including taking a list of objects, turning them into iterators by mapping iter over them, and then iterating over the list of iterators.
- It manipulates the iterators directly, by calling the next() function explicitly. Usually I'd think about the implementation of iterators involving the next() method only when considering writing an unusual iterator, not when using an iterator.
- It uses a standard module that had escaped my attention, heapq for using a list as a sorted heap.
- It uses object methods as first-class objects that can be pushed into the heap along with the data to be sorted.
There's nothing like a succinct thought-provoking snippet to start your day.