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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
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

  1. Use `heapq.nsmallest(3, set(numbers))[-1]` for better performance on very large lists
  2. 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

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.