Python Program to Find N Largest Elements from a List
In this article, we will learn to find the n largest elements from a list in a python program.
We find n largest element using 2 different methods:
- Using traverse of the list
- Using sorting
Using traverse of the list
Explanation
- First, we declared the list and N.
- And then we declared the new list nLargest.
- Then we iterate the loop N times.
- And then we find the maximum number from the list by traversing and store it to the new list and remove from the original list.
- Then finally we print the new list that contains N largest number.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # list
list = [12, 13, 55, 21, 8]
N = 2
nLargest = [] for i in range(0, N): maximum = 0 for j in range(len(list)): if list[j] > maximum: maximum = list[j] list.remove(maximum) nLargest.append(maximum) # print the n largest element of the list print(nLargest) |
Output
[21, 55]
Using sorting
Explanation
- First, we declared the list and N.
- Then we sort the list using sort(0 function
- the new print the list from the last N number.
Program
1 2 3 4 5 6 7 8 | # list list = [12, 13, 55, 21, 8] N = 2 # sort the list list.sort() print(list[-N: ]) |
Output
[21, 55]