Python Practice › List Programs › Program 29
Second largest number
Write a Python program to find the second largest number in a list (ignoring duplicates).
Input
[10, 45, 32, 45, 18]
Output
32
Approach
- Remove duplicates, sort, take the second from the end.
Solution 1: sorting
numbers = [10, 45, 32, 45, 18]unique = sorted(set(numbers))print(unique[-2])Output
32
Line by line
Line 2
set removes the duplicate 45, otherwise the answer would wrongly be 45.
Solution 2: one pass
numbers = [10, 45, 32, 45, 18]first = second = float("-inf")for n in numbers: if n > first: first, second = n, first elif first > n > second: second = nprint(second)Output
32
Line by line
Line 2
Both start below any possible number.
Lines 4-5
A new maximum pushes the old one into second place.
Lines 6-7
Numbers between the two update only the second.
Learn the concept
New to this topic? Read the lesson, then come back.