Find the Second Largest Number in a List in Python

Finding the second largest element is a common interview problem. The key challenge is handling duplicates correctly.

Solution 1: Remove Duplicates, Then Sort

def second_largest(nums):
    unique = list(set(nums))
    unique.sort()
    return unique[-2]

print(second_largest([10, 20, 4, 45, 99, 99]))  # Output: 45

Solution 2: Using sorted() and set()

def second_largest_v2(nums):
    return sorted(set(nums))[-2]

print(second_largest_v2([3, 1, 4, 1, 5, 9, 2, 6]))  # Output: 6

Solution 3: Efficient Single Pass (No Sorting)

def second_largest_efficient(nums):
    first = second = float('-inf')
    for n in nums:
        if n > first:
            second = first
            first = n
        elif n > second and n != first:
            second = n
    return second if second != float('-inf') else None

print(second_largest_efficient([10, 20, 4, 45, 99]))  # Output: 45

Key Takeaway

Always remove duplicates before searching. For performance-critical code, use the single-pass O(n) approach instead of sorting (O(n log n)).

(Visited 1 times, 1 visits today)