Python programs · Lists
Python program to find the second largest number in a list
Finding the second largest value shows why you must think about repeated numbers.
Approach
- Read the numbers into a list.
- Remove repeats by turning the list into a set, then sort it.
- The second largest is the second item from the end.
The program
numbers = list(map(int, input().split())) unique = sorted(set(numbers)) if len(unique) < 2: print("There is no second largest value") else: print("Second largest:", unique[-2])
Sample run
Input
12 45 7 45 30
Output
Second largest: 30
How the code works
The number 45 appears twice. Without removing repeats, sorting would put two 45s at the end and the "second largest" would wrongly be 45. set() keeps one copy of each value, and sorted() puts them in order. unique[-2] is the second item from the end. The check for fewer than two values avoids an IndexError when every number is the same.
Try changing it
- Find the third largest value.
- Find the second smallest value.
Common mistakes
- Sorting without removing repeats.
- Using
numbers[1]after sorting from smallest to largest, which gives the second smallest.