Retrieve the two highest item from a list containing 100,000 integers

Use heapq.nlargest. This is the most flexible approach in case you ever want to handle more than just the top two elements.

Here’s an example.

>>> import heapq
>>> import random
>>> x = range(100000)
>>> random.shuffle(x)
>>> heapq.nlargest(2, x)
[99999, 99998]

Leave a Comment