Without using built-in functions like sort() or max() twice.
Find the second largest number in a list in python with explanation.
361
23-Apr-2025
Updated on 27-Apr-2025
Khushi Singh
25-Apr-2025Several approaches exist to locate the second largest number contained in a list within Python language. The following step-by-step method built into Python can help you find the second largest number. Following is a step-by-step breakdown of the code along with its explanation.
Explanation:
The descending order sorting of the list allows us to obtain the second element directly. Causing inefficiency in terms of time complexity is sorting the list since it operates at O(n log n) for an extended list.
A better and faster approach involves one single iteration of the list and maintaining a record of the largest pair of numbers during each pass. The O(n) time complexity of this method proves faster than other methods when working with extensive lists.
Code Example
Explanation of the Code:
Initialization:
Looping through the list:
Edge case:
Output
For the input list
[12, 35, 1, 10, 34, 1], the output will be:This method ensures that you only loop through the list once, making it an efficient solution.