How to Find the Third Smallest Element in a Python List
Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.
Python code
22 linesdef find_third_smallest(numbers):
if len(numbers) < 3:
return None
unique_sorted = sorted(set(numbers))
if len(unique_sorted) < 3:
return None
return unique_sorted[2]
if __name__ == "__main__":
sample = [5, 2, 8, 2, 9, 1, 7, 3]
result = find_third_smallest(sample)
print(f"Numbers: {sample}")
print(f"Third smallest (considering duplicates): {result}")
sample2 = [4, 1, 1, 2]
result2 = find_third_smallest(sample2)
print(f"Numbers: {sample2}")
print(f"Third smallest: {result2}")
Output
Numbers: [5, 2, 8, 2, 9, 1, 7, 3]
Third smallest (considering duplicates): 3
Numbers: [4, 1, 1, 2]
Third smallest: None
How it works
The sorted(set(numbers)) call first removes duplicate values using set(), then sorts the unique elements in ascending order. Because set() preserves only distinct values, duplicate occurrences don't affect the result — the third smallest distinct value is returned. The if len(numbers) < 3 check quickly exits when there aren't enough elements to begin with. The function returns None if fewer than three unique values exist, which is safer than raising an error in production code. This approach is clean and readable for moderate-sized lists, though the set() conversion may change order for non-hashable items.
Common mistakes
- Forgetting to remove duplicates, so the result is the third element from the original list including repeats
- Assuming the list always has at least three unique elements without checking
- Using `numbers[2]` directly on a sorted list index without verifying the length
Variations
- Use `heapq.nsmallest(3, set(numbers))[-1]` for better performance on very large lists
- Find the third smallest *including* duplicates by sorting without `set()` and taking `sorted(numbers)[2]`
Real-world use cases
- Identifying the third-highest priority item in a ranked queue of pending tasks.
- Choosing a fallback server from a sorted list of available endpoints by latency.
- Extracting the third-lowest price point from a marketplace dataset for thresholding.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.