Python Program to Find the Kth Largest Element in a List
Intermediate · Lists
The kth largest element is the value that would sit in position k if the list were sorted from largest to smallest, so k = 1 is the largest and k = 2 the second largest. This program sorts a copy of the list in descending order and picks position k, and the alternatives show a heap-based way and what changes when repeated values count only once.
Program
List: [7, 10, 4, 3, 20, 15, 10] Largest to smallest: [20, 15, 10, 10, 7, 4, 3] Kth largest element for k = 4: 10
How it works
sorted(numbers, reverse=True)makes a new list from largest to smallest.- Positions are counted from 1 but indexes from 0, so the kth largest is at index
k - 1. - The check
1 <= k <= len(numbers)stops an index error whenkis 0 or bigger than the list. - The value 10 appears twice and counts twice here, so the 4th largest is 10. The last alternative counts each value once instead.
Other ways to write it
Using heapq.nlargest()
The 4 largest numbers: [20, 15, 10, 10] Kth largest element for k = 4: 10
nlargest() keeps only the k biggest values as it reads the list, which is faster than sorting everything when the list is long and k is small.
Counting each value only once
Distinct values, largest first: [20, 15, 10, 7, 4, 3] Kth largest distinct value for k = 4: 7
If repeated values should count once, turn the list into a set first. Now the 4th largest is 7, not 10.
Try it yourself
Change the program to find the kth smallest element instead, by sorting from smallest to largest.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Find the Second Largest Number in a List
- Find the Largest and Smallest Number in a List
- Heap Sort
- Sort a List in Descending Order
- Swap Elements at Even and Odd Positions in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
- Reverse a List
- Count Occurrences of an Element in a List
All Python programs · CBSE class 12 practical file · Python exercises