How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?
Use heapq.nlargest. This is the most flexible approach in case you ever want to handle more than just the top two elements.
heapq.nlargest
Here's an example.
>>> import heapq >>> import random >>> x = range(100000) >>> random.shuffle(x) >>> heapq.nlargest(2, x) [99999, 99998]
1.4m articles
1.4m replys
5 comments
57.0k users