Second largest number
Write a Python program to find the second largest number in a list (ignoring duplicates).
[10, 45, 32, 45, 18]
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])32
Line by line
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)32
Line by line
Both start below any possible number.
A new maximum pushes the old one into second place.
Numbers between the two update only the second.
Learn the concept
New to this topic? Read the lesson, then come back.