Find the Second Largest Unique Number in a Python List

This Python function finds the second largest unique number from a list by converting it to a set, removing the maximum, and returning the new maximum.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

11 lines
Python 3.9+
def second_largest_unique(numbers):
    unique_numbers = set(numbers)
    if len(unique_numbers) < 2:
        return None
    unique_numbers.remove(max(unique_numbers))
    return max(unique_numbers)

if __name__ == "__main__":
    test_list = [4, 2, 9, 5, 2, 9, 1, 5]
    result = second_largest_unique(test_list)
    print(f"Second largest unique number: {result}")

Output

stdout
Second largest unique number: 5

How it works

The function first converts the input list to a set, which automatically removes duplicates, leaving only unique values. If the set has fewer than two elements, there is no second largest, so it returns None. Removing the maximum from the set leaves the second largest as the new maximum, which is then returned. This approach is efficient and simple, leveraging set operations for uniqueness and max for determination.

Common mistakes

  • Forgetting to handle the case when there are less than two unique numbers.
  • Returning the second largest including duplicates if not using a set.
  • Modifying the original list by not using a copy.
  • Assuming the list is sorted before using indexing.

Variations

  1. Sort the list in descending order after deduplication and pick the second element using sorted(set(numbers))[-2].
  2. Use a heap-based approach with heapq.nlargest(2, set(numbers)) to get the top two elements.

Real-world use cases

  • Finding the runner-up score in a competition from a list of participant scores.
  • Determining the second highest sales figure in a monthly report for trend analysis.
  • Identifying the second most frequent error code in application logs for prioritization.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.