Finding the largest number in a list is a classic beginner exercise, but finding the second largest trips a lot of people up — especially when the list has duplicate values. This post shows how to find it correctly in a single pass through the list, without sorting the whole thing.
The key idea is to track two running values as you scan the list once: the largest value seen so far, and the second largest. Whenever a new number beats the current largest, the old largest "shifts down" into the second-largest slot.
Python Program to Find the Second Largest Number in a List
numbers = [45, 22, 89, 7, 63, 90, 12, 90]
largest = second = float("-inf")
for num in numbers:
if num > largest:
second = largest
largest = num
elif num > second and num != largest:
second = num
print(f"Largest: {largest}")
print(f"Second Largest: {second}")
Output:
Largest: 90
Second Largest: 89
Notice the list has two 90s — the num != largest check makes sure a duplicate of the largest value doesn't accidentally get counted as the second largest. This one-pass approach runs in O(n) time, using a loop just once instead of sorting the whole list first.
Second Largest Number Using sorted()
If you don't need the O(n) guarantee, Python's built-in sorted() combined with set() (to drop duplicates) gives you a short one-liner:
numbers = [45, 22, 89, 7, 63, 90, 12, 90]
unique_sorted = sorted(set(numbers))
second_largest = unique_sorted[-2]
print(f"Second Largest (one-liner): {second_largest}")
Output:
Second Largest (one-liner): 89
This is shorter to write, but it's O(n log n) because of the sort — for large lists, the manual loop version above is the faster choice, and it's also what most interviewers want to see.
