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:

  1. Using traverse of the list 
  2. Using sorting


Using traverse of the list

Explanation

  1. First, we declared the list and N.
  2. And then we declared the new list nLargest.
  3. Then we iterate the loop N times.
  4. 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.
  5. 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

  1. First, we declared the list and N.
  2. Then we sort the list using sort(0 function
  3. 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]
Next Post Previous Post
No Comment
Add Comment
comment url