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.
Python code
17 linesdef 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
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
- Use `set.intersection` and `set.union` methods instead of operators
- 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
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.