Editor

Python Program to Find the Second Largest Number in a List

Beginner · Lists

The second largest number in a list is the biggest number that is smaller than the largest. If the largest value appears twice, as 45 does here, the second largest is the next different value. This program finds it in a single pass through the list, without sorting.

Program

second_largest_in_list.py
numbers = [12, 45, 7, 45, 31, 9]
largest = None
second = None
for num in numbers:
if largest is None or num > largest:
second = largest # the old largest moves to second place
largest = num
elif num != largest and (second is None or num > second):
second = num
print("List:", numbers)
print("Largest:", largest)
if second is None:
print("There is no second largest number")
else:
print("Second largest:", second)
Output
List: [12, 45, 7, 45, 31, 9]
Largest: 45
Second largest: 31

How it works

  1. largest and second start as None, meaning no number has been seen yet.
  2. When a number beats largest, the old largest drops to second place and the new number takes first place.
  3. A number that is not the largest but beats second becomes the new second largest.
  4. The check num != largest skips repeats of the largest value, so 45 is not counted twice.
  5. If every number in the list is the same, second stays None and the program says there is no second largest.

Another way to write it

Using set() and sorted()

Using set() and sorted()
numbers = [12, 45, 7, 45, 31, 9]
unique = sorted(set(numbers)) # remove duplicates, then sort
if len(unique) < 2:
print("There is no second largest number")
else:
print("Second largest:", unique[-2])
Output
Second largest: 31

The set drops the repeated 45, and after sorting the second largest sits second from the end. It is shorter, but sorting does more work than one pass.

Try it yourself

Change the program to find the second smallest number in the list.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises