Introduction to Sets in Python

Python : Sets

In Python, a set is an unordered collection of unique items. It is represented using curly braces `{}` or by using the `set()` function.

Unlike lists, sets are mutable i.e., we can add, remove or modify elements in the set. However, sets do not support indexing or slicing operations.

Sets are commonly used to perform mathematical set operations such as union, intersection, and difference.

Creating a Set in Python

We can create a set in Python by enclosing a comma-separated sequence of elements inside curly braces or by using the `set()` function.

``````#creating a set
set1 = {1, 2, 3, 4, 5}
set2 = set([4, 5, 6, 7, 8])
``````

Adding and Removing Elements in a Set

We can add elements to a set using the `add()` method and remove elements from a set using the `remove()` or `discard()` method.

``````#adding elements to a set
print(set1) # output: {1, 2, 3, 4, 5, 6}

#removing elements from a set
set1.remove(6)
print(set1) # output: {1, 2, 3, 4, 5}

``````

Set Operations in Python

Python sets support various mathematical set operations such as union, intersection, and difference. These operations can be performed using the corresponding set methods or operators.

Union of 2 sets in Python

The union of two sets `A` and `B` is a set that contains all the elements of `A` and all the elements of `B`. We can perform the union operation using the `union()` method or the `|` operator.

``````set1 = {1, 2, 3}
set2 = {3, 4, 5}

#performing union operation
set3 = set1.union(set2)
print(set3) # Output: {1, 2, 3, 4, 5}

#using the | operator
set4 = set1 | set2
print(set4) # Output: {1, 2, 3, 4, 5}
``````

Intersection of 2 sets in Python

The intersection of two sets `A` and `B` is a set that contains all the elements that are common to both `A` and `B`. We can perform the intersection operation using the `intersection()` method or the `& `operator.

``````set1 = {1, 2, 3}
set2 = {3, 4, 5}

#performing intersection operation
set3 = set1.intersection(set2)
print(set3) # Output: {3}

#using the & operator
set4 = set1 & set2
print(set4) # Output: {3}
``````