Python Practice › List Programs › Program 29

Second largest number

EasyList Programs · 29 of 100

Write a Python program to find the second largest number in a list (ignoring duplicates).

Advertisement
Input
[10, 45, 32, 45, 18]
Output
32

Approach

  1. Remove duplicates, sort, take the second from the end.

Solution 1: sorting

Python
numbers = [10, 45, 32, 45, 18]unique = sorted(set(numbers))print(unique[-2])
Output
32

Line by line

Line 2

set removes the duplicate 45, otherwise the answer would wrongly be 45.

Solution 2: one pass

Python
numbers = [10, 45, 32, 45, 18]first = second = float("-inf")for n in numbers:    if n > first:        first, second = n, first    elif first > n > second:        second = nprint(second)
Output
32

Line by line

Line 2

Both start below any possible number.

Lines 4-5

A new maximum pushes the old one into second place.

Lines 6-7

Numbers between the two update only the second.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment