How to find smaller and larger number in a list ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 2

How to find smaller and larger number in a list ?

lar_num=-1 small_num=0 list1=[12,32,-24,54,24,99,21,87,56,99,-99] for i in list1: if lar_num<i: lar_num=i elif small_num>i: small_num=i print(lar_num) print(small_num) #same prog but with smaller line of code using in built function print(max(list1)) print(min(list1))

26th Mar 2021, 8:56 PM
Somnath Das
Somnath Das - avatar
2 Answers
+ 3
Problem with your code is that it will fail if: all elements are negative , strictly increasing sequence, only one element etc. Possible corrections: set initial values of smallnum larnum as +inf, -inf respectively, and change elif to if because same element can be both smallnum and larnum. By inf I mean a large number which exceeds maximum absolute value that can be present on list.
27th Mar 2021, 2:51 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
Try setting both lar_num and small_num to the first element of the list before the loop then loop over the remianing elements of the list. You can slice the list to just loop over the elements from index 1 to the end. list1[1:] Another option is to sort the list and then just get the first element as the smallest and the last element as the largest. And then of course you can use the min() and max() functions.
26th Mar 2021, 11:29 PM
ChaoticDawg
ChaoticDawg - avatar