This generator will sort only the requested part of a list. Useful for getting just the first few elements of a list and avoiding the overhead of sorting the whole thing.
1 2 3 4 5 6 7 8
import heapq def isorted(iterable): lst = list(iterable) heapq.heapify(lst) pop = heapq.heappop while lst: yield pop(lst)
This second version is by Raymond Hettiger, and is both simpler and faster than my original one, based on a generator-based quicksort.
The name isorted follows the convention from the itertools package and mimics the new python 2.4 "sorted" builtin.
Hope this is useful for someone, I needed more than once something like this.