The second largest number is the biggest number that is smaller than the maximum. Repeated values need care: in [99, 45, 99] the answer is 45, not 99.
The program
python
def second_largest(numbers): unique = set(numbers) if len(unique) < 2: return None unique.remove(max(unique)) return max(unique) print(second_largest([10, 20, 4, 45, 99])) print(second_largest([99, 45, 99])) print(second_largest([7, 7, 7]))
output
45 45 None
How it works
set(numbers)removes repeated values, so the maximum appears only once.- If fewer than 2 different values are left, there is no second largest, and the function returns
None. unique.remove(max(unique))takes out the largest value. The largest value that is left is the answer.
A common shortcut is sorted(numbers)[-2]. It gives 99 for [99, 45, 99], which is wrong, and it raises an IndexError for a list with one item.
Another way: one pass, no sorting
This version reads the list once and keeps the two largest different values seen so far:
python
def second_largest(numbers): first = None second = None for n in numbers: if first is None or n > first: first, second = n, first elif n != first and (second is None or n > second): second = n return second print(second_largest([10, 20, 4, 45, 99])) print(second_largest([99, 45, 99])) print(second_largest([5]))
output
45 45 None
When a new largest number arrives, the old largest moves down to second. first, second = n, first does both steps in one line.