How to Compute Jaccard Similarity in Python

Compute the Jaccard similarity between two lists by converting them to sets and dividing the intersection size by the union size.

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

Python code

17 lines
Python 3.9+
def jaccard_similarity(list1, list2):
    set1 = set(list1)
    set2 = set(list2)
    
    intersection = set1 & set2
    union = set1 | set2
    
    if not union:
        return 0.0
    
    return len(intersection) / len(union)

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5]
    b = [3, 4, 5, 6, 7]
    
    print(f"Jaccard similarity: {jaccard_similarity(a, b):.4f}")

Output

stdout
Jaccard similarity: 0.4286

How it works

This function first converts each input list to a set, which removes duplicates and enables O(1) membership tests. The intersection is computed with the & operator and the union with |. If the union is empty (both sets are empty), the function returns 0.0 to avoid division by zero. Finally, the ratio of intersection to union gives the Jaccard coefficient, a value between 0 and 1 where 1 means identical sets and 0 means no overlap.

Common mistakes

  • Forgetting to convert lists to sets before using set operations
  • Not handling the case where both sets are empty, causing a ZeroDivisionError
  • Assuming the function preserves order or elements from the original lists

Variations

  1. Use `set.intersection` and `set.union` methods instead of operators
  2. Compute Jaccard distance as `1 - jaccard_similarity`

Real-world use cases

  • Comparing product descriptions or user profiles to recommend similar items.
  • Measuring the similarity between two documents based on the sets of words they contain.
  • Evaluating the overlap of customer segments or feature sets in analytics pipelines.

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.