Python Program to Find Second Largest Number in a List (original) (raw)

Last Updated : 28 Oct, 2025

Given a list of numbers, the task is to find the second largest element in that list.

**For example:

li = [10, 20, 4, 45, 99] -> Second largest number = 45
li = [5, 8, 12, 3, 7] -> Second largest number = 8

Let's explore other different method to find second largest number in a list.

Using Loop

Use a loop (for loop) to iterate over the list and keep two variables **max1 and **max2 to keep track of largest and second largest number of list.

Python `

a = [10, 20, 4, 45, 99] max1 = max2 = float('-inf') for n in a: if n > max1: max2 = max1
max1 = n
elif n > max2 and n != max1: max2 = n
print(max2)

`

**Explanation:

Using heapq.nlargest()

This method uses a heap data structure to directly extract the top k largest elements efficiently. By finding the two largest elements (k = 2), the second element of the result will be the second largest number.

Python `

import heapq a = [10, 20, 4, 45, 99] res = heapq.nlargest(2, a) print(res[1])

`

**Explanation:

**Note: This approach is quick and efficient when we need to find the largest k elements.

Using Sorting

It sorts the list in descending order and picks the element at index 1, which becomes the second largest. While easy to implement, sorting the entire list takes extra time compared to other approaches.

Python `

a = [10, 20, 4, 45, 99] a.sort(reverse=True) print(a[1])

`

**Explanation:

**Note: While this method is simple but sorting the list can be less efficient when dealing with large datasets.