Open In App

Python program to find second largest number in a list

Last Updated : 01 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will explore various methods to find second largest number in a list. The simplest way to find is by using a loop.

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.

a = [10, 20, 4, 45, 99]

# Initialize largest (max1)
# and second largest (max2) to negative infinity
max1 = max2 = float('-inf')

# Loop through each number in list
for n in a:
  
    # If the current number is greater 
    # than largest found so far
    if n > max1:
      
        # Update second largest to the previous largest
        max2 = max1  
        
        # Update largest to the current number
        max1 = n     
        
    # If current number is less than largest
    # but greater than second largest
    elif n > max2 and n != max1:
      
        # Update second largest to current number
        max2 = n  

print(max2)

Output
45

Let’s explore other different method to find second largest number in a list:

Using Sorting

One of the simplest ways to find the second largest number is by sorting list in descending order. Once the list is sorted the second largest number will be at index 1.

a = [10, 20, 4, 45, 99]

# Sorting the list in descending order
a.sort(reverse=True)

# Second largest number will be at index 1
print(a[1])

Output
45

Explanation:

  • The list is sorted in descending order with a.sort(reverse=True).
  • The largest number is at index 0 and the second largest is at index 1.

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

Using heapq.nlargest()

The heapq.nlargest() function provides a simple and efficient way to find the largest elements in a list. We can use it to find the two largest numbers and access the second largest directly.

import heapq

a = [10, 20, 4, 45, 99]

# Get the two largest numbers using heapq.nlargest
top_two = heapq.nlargest(2, a)

# The second largest number is at index 1
print(top_two[1])

Output
45

Explanation:

  • heapq.nlargest(2, a) returns the two largest numbers from the list.
  • The second largest number is at index 1 of the returned list.

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



Similar Reads

three90RightbarBannerImg