python

Get the second largest number from a list in Python

Finding the second largest number from a python list can be implemented by using the methods described in this post.

# Funtion that will return the second largest number
def second_largest_num(num_list):
    ctr = 0
    y1 = y2 = float('-inf')

    for x in num_list:
        ctr += 1
        if x > y2:
            if x >= y1:
                y1, y2 = x, y1            
            else:
                y2 = x

    return y2 if ctr >= 2 else None

# Define the list
num_list = [30, 50, 90, 40, 60, 80]

# Get the second largest number
result = second_largest_num(num_list)

# Print the result
print(result)

# -> 80

We are using for loop here to find the second largest number from a Python List. We have created a function second_largest_num() and passed the list to it and it will return the second largest number from that list.

Find second-largest number using sorted() function

We can also use Python sorted() function to find the second largest number from a list. We need to pass the list to the sorted() function and get the second last item from the list and it will be the second-largest number in the list.

Code Example

num_list = [30, 50, 90, 40, 60, 80]

result = sorted(num_list)[-2]

print(result)

Output

80

Get second-largest number using nlargest() function of heapq module

We can use heapq module of Python and import the nlargest() function and it can be used to find the second largest number from the list. 

Code Example to get the second largest number using largest()

import heapq

numbers = [30, 34, 70, 50, 20, 40]

result = heapq.nlargest(2, numbers)

print(result[1])

Output

50
Was this helpful?