Write Python. Understand every error.

Open the editor

Python programs · Lists

Python program to find the second largest number in a list

Finding the second largest value shows why you must think about repeated numbers.

Approach

  1. Read the numbers into a list.
  2. Remove repeats by turning the list into a set, then sort it.
  3. The second largest is the second item from the end.

The program

numbers = list(map(int, input().split()))
unique = sorted(set(numbers))
if len(unique) < 2:
    print("There is no second largest value")
else:
    print("Second largest:", unique[-2])

Sample run

Input
12 45 7 45 30
Output
Second largest: 30

Run this program in Py-CRAFT

How the code works

The number 45 appears twice. Without removing repeats, sorting would put two 45s at the end and the "second largest" would wrongly be 45. set() keeps one copy of each value, and sorted() puts them in order. unique[-2] is the second item from the end. The check for fewer than two values avoids an IndexError when every number is the same.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: