Home âē Python programs
Second Largest Number in a List in Python
ā¤ā¤¸āĨ Hindi ā¤ŽāĨ⤠ā¤Ēā¤ĸā¤ŧāĨā¤
Problem statement
Find the second largest number in a list. Watch the definition: in [12, 45, 45, 2], the second largest is 45 only if duplicates count; when "second distinct" is meant, it is 12. Handle both readings deliberately.Approach 1: simple loop
Remove the maximum, then take the maximum of what remains â the two-step version that reads exactly like the problem statement.
nums = [12, 45, 2, 41] copy = nums[:] # keep the original untouched copy.remove(max(copy)) # drop ONE occurrence of the largest print(max(copy)) # Output: 41
remove() deletes only the first matching occurrence, so duplicates of the maximum survive â which is what the "duplicates count" reading wants. Work on a copy so the original list is intact for later use.
Approach 2: reusable function
For the distinct reading, collapse duplicates with a set first, sort, and pick the second from the end â the version most exams and interviews mean.
nums = [12, 45, 45, 2] unique = sorted(set(nums)) print(unique[-2]) # Output: 12
Build it defensively and the edge cases say their names: a list with fewer than two distinct values has no second largest at all.
def second_largest(nums):
unique = sorted(set(nums))
if len(unique) < 2:
return None # explicitly: there is no answer
return unique[-2]Approach 3: Pythonic alternative
One pass, two variables: walk the list once, tracking the largest and second largest seen so far. This is the version that scales â it also works streaming over data you cannot sort.
nums = [12, 45, 2, 41]
first = second = float("-inf")
for n in nums:
if n > first:
second = first # old champion demoted
first = n
elif first > n > second:
second = n
print(second)
# Output: 41Starting both at negative infinity means any real number beats them â even a list of all-negative numbers works. Note the chained comparison first > n > second, which skips duplicates of the champion.
Dry run
Trace the one-pass version over [12, 45, 2, 41]. Start: first = -inf, second = -inf. n=12: 12 > -inf â second stays -inf, first = 12. n=45: 45 > 12 â second = 12, first = 45. n=2: not > 45; is 45 > 2 > 12? No â 2 does not beat 12, skip. n=41: not > 45; is 45 > 41 > 12? Yes â second = 41. Answer: 41. Every number had exactly one comparison path â that is what "one pass" buys.
Common errors
- Sorting the original list in place (
nums.sort()) â the surrounding program may still need the original order; sort a copy or usesorted(). - Picking
sorted(nums)[-2]when duplicates of the maximum exist â with [12, 45, 45, 2] that returns 45, not the second distinct value. Decide which definition you need. - Initialising second largest to 0 â breaks on all-negative lists; use
float("-inf")or the first two elements. - Forgetting the too-short list:
[7]or[7, 7](distinct reading) has no second largest â return None instead of crashing. - Demoting without saving â
second = firstmust happen beforefirst = n, or the old champion is lost.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: