Second Largest Number in PythonWhen we have a lot of elements in our list, the thought of finding the highest or lowest element can come to our mind and Python has made it much easier for us. In this article, we shall how we can use to find the second largest number in Python from a list.
Let us have a look at the first approach- Sorting the list and then print the second last numberThe following program illustrates how we can do it in Python- Example - Output: The second largest element of the list is: 30 It's time to go for the explanation part-
The second method is to obtain the second largest element of the list by removing the maximum element. Let us see how we can do it. Removing the maximum elementExample - Output: 30 Explanation - Let us understand what we have done in the above program-
In the third method, we will use for loop and find the second largest number from the list. Example - Output: Enter number of elements in list: 5 Enter the elements: 10 Enter the elements: 20 Enter the elements: 30 Enter the elements: 40 Enter the elements: 50 The second largest element is: 40 Explanation - Let us have a glance at what we have done here-
Traversing the listIn the last program, we will traverse the list to find out the largest number and then make use of conditional statements to find the second largest number from the list. The following program illustrates the same- Example - Output: 30 Explanation - Let us understand what we have done in the above program-
So, in this article, we got the chance to think out of the box and discover some new ways to develop the logic for finding the second largest number in Python. Next TopicDefaultdict in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India