Nowadays I would recommend heapq.nlargest(n, iterable, key=None)
.
Example:
import heapq
task_ids = [(task_id, score) for task_id, score in task_data]
top_task_ids = heapq.nlargest(batch_size, task_ids, key=lambda x: x[1])
And certainly there is heapq.nsmallest
.
Offical docs: heapq — Heap queue algorithm — Python documentation.