I’d like to create a list maxValues containing top 20 values from a list of integers lst.
maxValues = []
for i in range(20):
maxValues.append(max(lst))
lst.remove(max(lst))
Is there a more compact code for achieving this task or even built-in function?
There’s
heapq.nlargest():From the doc:
Or at the same way use
heapq.nsmallest()if you want the smallest.IMPORTANT NOTE from the doc: