Editor

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

kth_largest_element.py
numbers = [7, 10, 4, 3, 20, 15, 10]
k = 4 # or: k = int(input("Enter k: "))
print("List:", numbers)
if 1 <= k <= len(numbers):
ordered = sorted(numbers, reverse=True) # largest first; numbers is unchanged
print("Largest to smallest:", ordered)
print(f"Kth largest element for k = {k}:", ordered[k - 1])
else:
print("k must be between 1 and", len(numbers))
Output
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

  1. sorted(numbers, reverse=True) makes a new list from largest to smallest.
  2. Positions are counted from 1 but indexes from 0, so the kth largest is at index k - 1.
  3. The check 1 <= k <= len(numbers) stops an index error when k is 0 or bigger than the list.
  4. 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()

Using heapq.nlargest()
import heapq
numbers = [7, 10, 4, 3, 20, 15, 10]
k = 4
top_k = heapq.nlargest(k, numbers)
print(f"The {k} largest numbers:", top_k)
print(f"Kth largest element for k = {k}:", top_k[-1])
Output
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

Counting each value only once
numbers = [7, 10, 4, 3, 20, 15, 10]
k = 4
distinct = sorted(set(numbers), reverse=True) # the set drops the second 10
print("Distinct values, largest first:", distinct)
print(f"Kth largest distinct value for k = {k}:", distinct[k - 1])
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises