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.

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

Python code

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

stdout
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

  1. Use `items.count(e)` in a loop for each unique element, but this is O(n^2).
  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

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.