Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Second Largest

Medium · 50 XP

Print the second-largest distinct value in the starter list.

Target output
23
Blank · autosaved
PYsecond-largest.py
Run your code to check it…
Guide

How to approach Second Largest

The word that matters in the prompt is distinct. The list contains 42 twice, so the second-largest value is not the second item of the sorted list: it is the second-largest value once duplicates are gone.

set(nums) removes duplicates, sorted() puts what remains in ascending order, and index [-2] takes the second from the end. That is short and readable. A single pass that tracks the best and second-best values seen so far is the version to know for very large inputs, because it never sorts.

Worked through on this data

  1. nums is [17, 42, 8, 42, 23, 4, 23]. The set of distinct values is {4, 8, 17, 23, 42}.
  2. Sorted, that is [4, 8, 17, 23, 42]. Index -1 is 42, index -2 is 23.
  3. The program prints 23. Without the set, the sorted list ends [..., 23, 42, 42] and index -2 is 42, which is wrong.

Common mistakes

  • Forgetting to deduplicate returns the largest value again whenever it appears twice.
  • nums.sort() sorts the list in place and returns None, so nums.sort()[-2] raises a TypeError.
  • A list with fewer than two distinct values (such as [5, 5]) makes [-2] raise an IndexError. Decide what the function should return in that case.

Time and space

Building the set is O(n) and sorting it is O(k log k) for k distinct values. The single-pass version is O(n) time and O(1) space.

Where this shows up

Ranking with ties is everywhere: the runner-up in a leaderboard, the second-highest bid in an auction, the next-best price. Deciding how duplicates count is always part of the spec.

Take it further

Solve it in one pass with two variables, first and second, and no sorting. Then generalise to the k-th largest with heapq.nlargest.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path