How to Count Distinct Elements in a List in Python
Count the number of unique items in a list by converting it to a set and returning its length.
Python code
7 linesdef count_distinct_elements(items):
return len(set(items))
if __name__ == "__main__":
sample = [1, 2, 3, 2, 1, 4, 3, 5, 4, 6]
result = count_distinct_elements(sample)
print(result)
Output
6
How it works
The set(items) call removes all duplicate values, leaving only unique elements. len() then returns the count of those unique elements. This is the simplest and most efficient way to count distinct items for hashable types, with O(n) time complexity and O(n) space. The code works for any iterable of hashable objects, such as strings, numbers, or tuples.
Common mistakes
- Forgetting that sets only work with hashable items; unhashable types like lists or dicts will raise a TypeError.
- Using a manual loop with an empty list and checking for membership, which is slower and more error-prone.
- Not considering that the order of elements is lost when converting to a set, which is irrelevant for counting.
Variations
- Use `items.count(e)` in a loop for each unique element, but this is O(n^2).
- Use `collections.Counter` if you also need the frequency of each distinct element.
Real-world use cases
- Count unique visitors from a list of user IDs in a log file.
- Determine the number of distinct tags or categories in a dataset before analysis.
- Validate that a list of order numbers contains no duplicates by comparing lengths.
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.