Second largest number
EasyList Programs · 29 of 100
Write a Python program to find the second largest number in a list (ignoring duplicates).
Input[10, 45, 32, 45, 18]
Approach
- Remove duplicates, sort, take the second from the end.
Solution 1: sorting
Python
numbers = [10, 45, 32, 45, 18]unique = sorted(set(numbers))print(unique[-2])
Line by line
Line 2set removes the duplicate 45, otherwise the answer would wrongly be 45.
Solution 2: one pass
Python
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)
Line by line
Line 2Both start below any possible number.
Lines 4-5A new maximum pushes the old one into second place.
Lines 6-7Numbers between the two update only the second.
Learn the concept
New to this topic? Read the lesson, then come back.
More list programs
← All 100 List Programs