How to find kth largest element of a list in Python
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 orderarr = sorted(arr, reverse=True)# retrieval of the kth (k=3) largest elementk=3print ("kth largest element:", arr[k-1])
Explanation
- Line 1: We declare a list,
arr, and initialize it with elements. - Line 4: We use the
sortedfunction to sort the elements ofarrin descending order. - Lines 7–8: We declare a variable,
k, and initialize it with a value of3. Next, we print the third largest element ofarrby retrieving the element at indexk-1.