Zed-King Institute

    Python Program to Find the Second Largest Number in a List

    mediumListsPython

    Once a list is sorted, its largest numbers sit at the end — and negative indexes count from the end.

    The question

    Read a line of different integers separated by spaces and print the second largest number.

    The code

    program.py

    nums = list(map(int, input().split()))
    nums.sort()
    print("Second largest =", nums[-2])

    Input

    52 95 31 35 23 19 86

    Output

    Second largest = 86

    How it works

    1. 1Read the numbers into a list.
    2. 2nums.sort() arranges them from smallest to largest.
    3. 3nums[-1] is the largest, so nums[-2] is the second largest.

    Common mistakes

    • Using nums[1], which is the second smallest, not the second largest.
    • Writing nums = nums.sort() — sort() returns None, so the list is lost.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Lists