Python Program to Find Second Largest Number in a List

In this Python program, we’ll create a program that finds the second largest number in a list of integers. We’ll walk through the problem statement, the program itself, how it works, and provide input-output examples.

Problem Statement:

Python Program to Find Second Largest Given a list of integers, we want to find the second largest number in the list.

Python Program to Find Second Largest Number in a List

def second_largest(numbers):
    if len(numbers) < 2:
        return "List should contain at least two numbers."
    
    largest = second = float('-inf')
    
    for num in numbers:
        if num > largest:
            second = largest
            largest = num
        elif num > second and num != largest:
            second = num
    
    if second == float('-inf'):
        return "There is no second largest element."
    
    return second

# Input list of numbers
num_list = [12, 45, 2, 41, 31, 10]
result = second_largest(num_list)
print("The second largest number is:", result)

How it Works:

  1. The function second_largest takes a list of numbers as input.
  2. It initializes two variables largest and second with negative infinity using float('-inf').
  3. It iterates through each number in the list.
  4. If the current number is greater than the largest number, it updates second with the value of largest and updates largest with the current number.
  5. If the current number is greater than second and not equal to largest, it updates second with the current number.
  6. After iterating through all numbers, it checks if second is still equal to negative infinity, which means there is no second largest element in the list.
  7. Finally, the function returns the second largest number.

Input-Output:

Input:

[12, 45, 2, 41, 31, 10]

Output:

The second largest number is: 41

Input:

[5, 5, 5, 5]

Output:

There is no second largest element.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...