Sets in Python – Differece, Symetric Difference, Union, Intersection

After writing the article scraping a web site up to the N-th level with Python, I have decided to summarize what could be achieved with Set() in this language. Pretty much, sets can be described as lists with a few differences:

Set == List

• Set is iterable
• Set is mutable+
• If the set is frozenset, it is immutable

Set != List

• Set is extremely faster for checking if an element exists (it is HashTable)
• Set is unordered
• Set can only have unique elements

Result:

Frozenset

The frozenset is an immutable set. Thus, once it is created, it cannot be immuted. Thus, even if the .copy() function is not used and simply frozen_first_set = frozenset(first_set) is carried out, the frozen set is not changed, once the initial set is changed. Which is not the case with the test_set :

Result:

Set Union

Uniting two sets gives a new set, which consists of the unique values of these two sets. Makes sense.

Result:

Set Intersection

Intersection is tricky. It only returns the set of elements, which are present in both sets.

Result:

Set Symmetric Difference

This is the difference of the two sets. E.g., everything, which is not part of the intersection sets, for both sets.

Result:

Set Difference

Difference is a bit tricky. It takes the first set and compares it with the second set. Then the returned set contains everything from the second set, which is not in the first.

Result:

That’s all!

Tagged with: , , , ,