How to print the top 3 largest values from a list in Python

2 Answers

0 votes
import sys

def printTop3(lst):
    lenn = len(lst) 
    if (lenn < 3):
        return
     
    first = second = third = -sys.maxsize
     
    for i in range(0, lenn):
        if (lst[i] > first):
            third = second
            second = first
            first = lst[i]
        elif (lst[i] > second):
            third = second
            second = lst[i]
        elif (lst[i] > third):
            third = lst[i]
     
    print(first, second, third)
 

lst = [12, 98, 80, 50, 88, 35, 70, 60, 97, 85, 89]

printTop3(lst)




'''
run:

98 97 89

'''

 



answered Jun 10, 2021 by avibootz
0 votes
from heapq import nlargest
 
lst = [12, 98, 80, 50, 88, 35, 70, 60, 97, 85, 89]
 
top3 = nlargest(3, lst)
 
print(top3[0])
print(top3[1])
print(top3[2])
 
 
 
 
'''
run:
 
98
97
89
 
'''

 



answered Jun 10, 2021 by avibootz

Related questions

1 answer 158 views
1 answer 148 views
1 answer 153 views
1 answer 129 views
1 answer 137 views
1 answer 149 views
2 answers 168 views
...