Second Largest number in a List – Python Way
In this code, we will find out the second largest number from a list of integer numbers. There are several ways to do this. The first approach is as follows
lst = [34, 56, 56, 56, 45, 2, 4, 12, 45] x= for i in lst: if i not in x: x.append(i) lar = max(x) x.remove(lar) lar = max(x) print('Second Largest no ',lar)
The above approach first of all generates a second list with unique values and then removes the largest number from that list. In the above approach, we used the max() function and remove method to do the needful. The same we can do with the help of built-in python datatype set(). As we are well aware that set contains only the unique values thus the list is now converted into set and then again converted into list and
lst = [34, 56, 56, 56, 45, 2, 4, 12, 45] x= list(set(lst)) lar = max(x) x.remove(lar) lar = max(x) print('Second Largest no ',lar)
How do you like these two methods to find out the second largest number in a list? If you have any better solution then please contact us.