How to calculate Jaccard similarity and distance in Python

Home / python / How to calculate Jaccard similarity and distance in Python
Published on August 25, 2026
Updated on September 2, 2026
2 min read

problem

You want to calculate the Jaccard similarity and distance using Python.

Similarity formula:

Jaccard similarity maths formula

Distance formula (or dissimilarity if you like):

Distance = 1 - J(A, B)

SOLUTION

Given two sets, we can calculate their similarity as follow:

  1. First, calculate the intersection and the union of the sets. 
  2. Then, we divide the count of intersections by the counts of the union. 

 

In Python, we can easily do this by using the built-in sets. 

jaccard.py
				
					
def jaccard_similarity(set_a:set, set_b:set):

    inter = set_a.intersection(set_b)
    union = set_a.union(set_b)

    count_inter = len(inter)
    count_union = len(union)

    similarity = count_inter / count_union

    return similarity

				
			
running

Let’s create a main method to call this function, and also calculate distance, then print results.

jaccard.py
				
					
if __name__ == '__main__':
    a = {1, 2, 3, 4, 5, 6, 8, 9, 10}
    b = {1, 3, 5, 8}

    s = jaccard_similarity(a, b)
    d = 1 - s

    print("Jaccard Similarity: ", s)
    print("Jaccard Distance: ", d)


				
			
output
output of jaccard similarity and distance (numbers example)
Example with words
jaccard.py
				
					a = {"red", "blue", "green", "yellow", "white"}
b = {"green"}
				
			
running
jaccard.py
				
					
if __name__ == '__main__':

   a = {"red", "blue", "green", "yellow", "white"}
   b = {"green"}

   s = jaccard_similarity(a, b)
   d = 1 - s

   print("Jaccard Similarity: ", s)
   print("Jaccard Distance: ", d)
				
			
output
output of jaccard similarity and distance (strings example) in Python
complete code
jaccard.py
				
					
def jaccard_similarity(set_a:set, set_b:set):

    inter = set_a.intersection(set_b)
    union = set_a.union(set_b)

    count_inter = len(inter)
    count_union = len(union)

    similarity = count_inter / count_union

    return similarity


if __name__ == '__main__':

    a = {"red", "blue", "green", "yellow", "white"}
    b = {"green"}

    s = jaccard_similarity(a, b)
    d = 1 - s

    print("Jaccard Similarity: ", s)
    print("Jaccard Distance: ", d)


				
			

conclusion

In this post we saw how to easily calculate Jaccard similarity and distance given two sets in Python. This is used for example to compare the similarity of two text documents, also in recommendation systems, text mining, Natural Language Processing and more.

 

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪