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.
Python code
11 linesdef 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
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
- Sort the list in descending order after deduplication and pick the second element using sorted(set(numbers))[-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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.