PythiloLesson 18 of 32 · progress kept in this browser

Pick the k smallest with heapq

Python's heapq module implements the heap from the previous lesson on plain lists. heapify arranges a list in linear time, and heappop returns the smallest item in logarithmic time.

import heapq
scores = [42, 7, 19, 3]
heapq.heapify(scores)
print(heapq.heappop(scores))   # 3
Your task

Write k_smallest(items, k) returning the k smallest values in ascending order using heapq, without modifying items. If k exceeds the length, return all values sorted.