[Tutor] Getting greatest 3 numbers from list
Manprit Singh
manpritsinghece at gmail.com
Mon Feb 21 06:29:44 EST 2022
Dear Sir,
My problem is to get greatest 3 numbers from list, list ls along with
solution given below:
ls = [2, 4, 9, 6, 3, 9, 6, 1]
sorted(set(ls))[-3:]
gives the right answer
[4, 6, 9]
Tried it with a for loop, just thinking why i am producing a sorted list , for
only getting largest 3 items
lmax = []
ls = [2, 4, 9, 6, 3, 9, 6, 1]
for _ in range(3):
mx = ls[0]
for ele in ls[1:]:
if ele > mx and ele not in lmax:
mx = ele
lmax.append(mx)
print(lmax)
gives the correct answer
[9, 6, 4]
This problem be done with a for loop more easily ? i know it is not a good
question - my apologies
Regards
Manprit Singh
More information about the Tutor
mailing list