Python Program to Find the Second Largest Number in a List
sorted(set(nums))[-2]."Second largest" sounds like a small variation on finding the largest number, but duplicates make it tricky. In [9, 9, 5] the second largest value is 5, not 9. A solution that ignores this is wrong.
This page shows the short solution using a set, a one-pass solution that tracks the top two values without sorting, and how to handle lists with fewer than two distinct numbers.
| Input | A list of numbers, e.g. [10, 40, 25, 40] |
|---|---|
| Output | The second largest distinct value, or a message if there is none |
| Approach | Remove duplicates and sort, or track the top two values in one pass |
| Time complexity | O(n log n) with sorting, O(n) with one pass |
Approach to find the second largest number step by step
- Convert the list to a set so each value appears once.
- If the set has fewer than two items, there is no second largest value; report that.
- Sort the unique values in ascending order.
- The second largest is the item at index
-2.
The one-pass version replaces sorting with two variables, first and second, updated as you scan.
How the second largest code works
set(nums) throws away repeated values, so [10, 40, 25, 40] becomes {10, 25, 40}. sorted() turns that into the list [10, 25, 40], and [-2] selects 25.
The one-pass loop handles three cases for each number n: it is bigger than first (so the old first becomes second), it lies between second and first, or it is ignored. The n != first check stops a duplicate of the maximum from becoming the second value.
nums = [10, 40, 25, 40]
unique = sorted(set(nums))
print(unique)
print(unique[-2])Other ways to get the second highest value
You can also remove the maximum with list.remove() and call max() again, but remove() deletes only the first copy, so duplicates of the maximum break it unless you remove them all. heapq.nlargest(2, unique)[-1] is neat for large lists. Whatever you choose, test with duplicates and with a list that has only one distinct value.
Examples you can run
Press Run, then edit the code and run it again.
Second largest with set and sorted
Unique values, sorted, then index -2.
def second_largest(nums):
unique = sorted(set(nums))
if len(unique) < 2:
return None
return unique[-2]
print(second_largest([10, 40, 25, 40]))
print(second_largest([9, 9, 5]))
print(second_largest([7, 7, 7]))Expected output25
5
None
Single pass without sorting
Track first and second as you scan; use None for "not found yet".
def second_largest(nums):
first = second = None
for n in nums:
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([3, 8, 1, 8, 6]))
print(second_largest([-4, -1, -9]))Expected output6
-4
Edge cases: short lists
An empty list or a one-item list has no second largest value.
def second_largest(nums):
unique = sorted(set(nums))
return unique[-2] if len(unique) >= 2 else None
print(second_largest([]))
print(second_largest([5]))
print(second_largest([5, 2]))Expected outputNone
None
2
Interactive version
Read integers from one line and print the answer.
line = input("Numbers: ")
unique = sorted({int(x) for x in line.split()})
if len(unique) < 2:
print("No second largest number")
else:
print("Second largest:", unique[-2])Expected outputNumbers: 20 85 85 40 61
Second largest: 61
Common mistakes
Sorting without removing duplicates
✗ Wrong
nums = [9, 9, 5]
print(sorted(nums)[-2])✓ Right
nums = [9, 9, 5]
print(sorted(set(nums))[-2])Use set() first so each value counts once.
Indexing a list that is too short
✗ Wrong
nums = [7]
print(sorted(set(nums))[-2])✓ Right
nums = [7]
unique = sorted(set(nums))
print(unique[-2] if len(unique) >= 2 else "no second largest")Check len(unique) >= 2 before reading index -2.
Python Program to Find the Second Largest Number in a List: questions people ask
How do I find the second largest number in a list in Python?
Use sorted(set(nums))[-2]. The set removes duplicates, sorting puts the values in order, and [-2] picks the second from the end.
What if the largest number appears twice?
Then the second largest is the next smaller distinct value. In [9, 9, 5], it is 5. Converting to a set first gives that result.
Can I find the second largest without sorting?
Yes. Scan once while keeping the two biggest distinct values in variables. This runs in O(n) time and uses constant extra memory.
Keep learning
Step-by-step lessons:
Python ListsPython SetsPython Sorting
Related:
Python Program to Find the Largest Number in a ListPython sorted() FunctionHow to Remove Duplicates from a List in PythonPython List sort() Method
More in list and dictionary programs:
Python Program to Find the Largest Number in a ListPython Program to Calculate the Average of a ListPython Program to Flatten a Nested List of Any DepthPython Program to Transpose a MatrixPython Program to Merge Two Sorted Lists See all →