What is a Python Set?
- Sets contain collections of unique and distinct elements in Python. Sets are unordered, and the elements are not indexed. Sets are mutable, and you can add or remove elements from them.
- Sets can only contain one example of a given element.
- They behave like mathematical sets. For example, we can ask what is in the intersection of two sets (that is, contained in both sets) or in the union of two sets (that is, contained in either one of the sets).
- We often see information like this represented visually in a Venn Diagram.

Example of Python Sets:
- Sets are wrapped in curly braces {} and elements are separated by commas. Here is an example of two sets:
python
1set1 = {'a', 'b', 'c', 1, 2, 3}
2set2 = {'b', 'c', 'd', 3, 4, 5}
3print(set1 & set2)Output Example:
1{'c', 3, 'b'}- The & operator above on line 3 is used to find the intersection of two sets. The intersection are the elements c, 3, and b.
Finding the Union of Two Sets:
- The union of two sets is the set of elements that are in either set (i.e., the elements in both sets combined).
python
1set1 = {'a', 'b', 'c', 1, 2, 3}
2set2 = {'b', 'c', 'd', 3, 4, 5}
3print(set1 | set2)Output Example:
1{'a', 2, 3, 1, 4, 5, 'b', 'd', 'c'}Finding the Differences Between Two Sets:
- Whatβs in set1 that is not in set2?
python
1set1 = {'a', 'b', 'c', 1, 2, 3}
2set2 = {'b', 'c', 'd', 3, 4, 5}
3print(set1 - set2)Output Example:
1{1, 2, 'a'}Performing Set Lookups:
- We can check if an element is in a set using the in keyword.
- The lookup is very fast because sets are implemented as hash values.
python
1set1 = {'a', 'b', 'c', 1, 2, 3}
2set2 = {'b', 'c', 'd', 3, 4, 5}
3print(5 in set2)Output:
1True