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:
- The function
second_largest
takes a list of numbers as input. - It initializes two variables
largest
andsecond
with negative infinity usingfloat('-inf')
. - It iterates through each number in the list.
- If the current number is greater than the
largest
number, it updatessecond
with the value oflargest
and updateslargest
with the current number. - If the current number is greater than
second
and not equal tolargest
, it updatessecond
with the current number. - 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. - 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.