Home / Python / Example programs / Lists

Python program: Second largest number in a list

Find the second largest distinct number.

The code

nums = [10, 45, 45, 32, 8]

unique = sorted(set(nums), reverse=True)
print(unique[1] if len(unique) > 1 else None)

first = second = float("-inf")
for n in nums:
    if n > first:
        first, second = n, first
    elif first > n > second:
        second = n
print(second)

Output

32
32

How it works

Removing duplicates with a set first means 45 is not counted twice. The single-pass version is faster for huge lists.

Python features used

Learn the ideas behind it in the free lesson Lists & Tuples.