Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
lists
sorting
communitycreator

How to find kth largest element of a list in Python

Mahnoor Zaheer

Overview

A sorting algorithm can be used to find the kth largest element of a list in Python. If we sort the list in descending order, we can retrieve the element through indexing.

Example

arr = [23, 36, 12, 19, 10, 8, 66]

# sorting in descending order
arr = sorted(arr, reverse=True)

# retrieval of the kth (k=3) largest element
k=3
print ("kth largest element:", arr[k-1])
Finding the kth largest element of a list in Python

Explanation

  • Line 1: We declare a list, arr, and initialize it with elements.
  • Line 4: We use the sorted function to sort the elements of arr in descending order.
  • Lines 7–8: We declare a variable, k, and initialize it with a value of 3. Next, we print the third largest element of arr by retrieving the element at index k-1.

RELATED TAGS

python
lists
sorting
communitycreator
RELATED COURSES

View all Courses

Keep Exploring