Home › Interview Questions › Write a Python function to find the second largest…

Write a Python function to find the second largest number in a list.

🟢 Easy Coding Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

Here’s a straightforward implementation that sorts the list in descending order and returns the element at index 1. It works for lists with at least two distinct values.

python
def second_largest(nums):
    if len(nums) < 2:
        raise ValueError("List must contain at least two elements")
    # Sort in descending order
    sorted_nums = sorted(nums, reverse=True)
    return sorted_nums[1]

This solution runs in O(n log n) time because of the sort. If you need an O(n) solution, you can keep track of the largest and second largest values while iterating:

python
def second_largest(nums):
    first = second = float('-inf')
    for n in nums:
        if n > first:
            second = first
            first = n
        elif n > second and n != first:
            second = n
    if second == float('-inf'):
        raise ValueError("No second distinct largest value")
    return second

Both approaches correctly handle duplicates and return the second largest distinct number.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500