Search code examples
pythonperformanceset

Efficiently compare two sets in Python


I have two large integer sets, set1 and set2. Which one of the below is more efficient?

Example:

if(set1 == set2)

or

if(len(set1)==len(set2))

Solution

  • The two statements are completely different from each other.

    if(set1==set2) compares for equality of each element in both the sets, and evaluates to true if and only if both the sets are exactly same.

    Whereas if(len(set1)==len(set2)) compares only the length of both the sets. Even if you have two sets with same length there may be cases when they are not the same. For eg consider this:

    set1: [1, 3, 6, 29, 31]

    set2: [1, 3, 7, 10, 15]

    Though the sets have the same length they are not the same.

    You could do this to save on time.

    if len(set1) == len(set2):
        if set1 == set2:
            //TODO when sets are equal
        else
            //TODO when sets are not equal.
    else
        //TODO when sets are not equal