-4

Can someone help me writing a code in order to increasingly iterate on multiple iterators. As an example imagine that I have several lists (for example : [1, 9] and [2, 3, 4]) and I want to get an iterable from those lists yielding 1, 2, 3, 4 and 9. Of course the idea is to use more big and complex iterators (otherwise it is easy to just merge and sort).

Thank you !

Eliesls
  • 11
  • 1

1 Answers1

2

heapq is exactly designed for what you want : It creates an iterator, so you don't have to handle huge lists. Here is the code for a simple example :

import heapq
a = [1, 4, 7, 10]
b = [2, 5, 6, 11]
for c in heapq.merge(a, b): 
    print(c)

Of course, it works only if your lists are sorted, you have to sort them before if they are not sorted.