Search code examples
python-3.xpython-itertools

Taking first N items from two combined iterators?


I've got two iterables (i1 and i2). Each one is producing items sorted in order of a key, with both iterables using the same key. I want to get the first N items, still sorted by the key, from the combined iterations. If I was willing to completely consume both iterables, I could do:

l = list(i1) + list(i2)
l.sort()
l[:n]

but I know I'm only going to need a small fraction of that. Is there some neat way to do this using just itertools?


Solution

  • See Tim Peters's suggestion to use heapq.merge().