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.
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_largesttakes a list of numbers as input.
- It initializes two variables
secondwith negative infinity using
- It iterates through each number in the list.
- If the current number is greater than the
largestnumber, it updates
secondwith the value of
largestwith the current number.
- If the current number is greater than
secondand not equal to
largest, it updates
secondwith the current number.
- After iterating through all numbers, it checks if
secondis still equal to negative infinity, which means there is no second largest element in the list.
- Finally, the function returns the second largest number.
[12, 45, 2, 41, 31, 10]
The second largest number is: 41
[5, 5, 5, 5]
There is no second largest element.