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]
More Related Contents:
- How do I sort a list of dictionaries by a value of the dictionary?
- Why does “return list.sort()” return None, not the list?
- Sorting list based on values from another list
- How to sort a list of objects based on an attribute of the objects?
- What is the difference between `sorted(list)` vs `list.sort()`?
- From list of integers, get number closest to a given value
- sort() and reverse() functions do not work
- How to sort two lists (which reference each other) in the exact same way
- Finding median of list in Python
- Combining two sorted lists in Python
- Why does ‘.sort()’ cause the list to be ‘None’ in Python? [duplicate]
- Custom Python list sorting
- Sorting Python list based on the length of the string
- Does python have a sorted list?
- Sort multidimensional array based on 2nd element of the subarray
- Python – How to sort a list of lists by the fourth element in each list? [duplicate]
- Sort a list of lists with a custom compare function
- Python data structure sort list alphabetically
- Python .sort() not working as expected
- How to sort a list of objects based on an attribute of the objects in descending order?
- Sorting list according to corresponding values from a parallel list [duplicate]
- Given parallel lists, how can I sort one while permuting (rearranging) the other in the same way?
- Sort a list with a custom order in Python
- How to sort multidimensional array by column?
- How to sort a 2D list? [closed]
- Sort list while pushing None values to the end
- How can I sort a list, according to where its elements appear in another list?
- How to sort a list of dictionaries by a value of the dictionary in Python?
- Sort python list by function
- Rearranging list based on order of another list