# 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.
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.
num_list = [30, 50, 90, 40, 60, 80] result = sorted(num_list)[-2] print(result)
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)