PythonMastery
Python programs · Lists · beginner

Find the second largest number in a list in Python

Find the second largest number in a list in Python, with repeated values handled correctly, and a one-pass loop that works without sorting.

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

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.

Learn the idea: Lists & Sequences, Sets: Unordered, Unique, Lightning Fast, Functions & Scoping