BCA / B.Tech 6 min read

Set Operations in Python

Set Operations in Python:


In Python, a set is a powerful data structure that allows you to work with a collection of unique items. When working with sets, you can use various mathematical set operations. The most common among these are Union, Intersection, and Difference.

Union:
The union operation combines all unique items from two or more sets into a new set. This operation is used to get all items that are present in any of the sets. You can use the `union()` method or the `|` operator.

Intersection:
The intersection operation gets the items that are common to both sets. This operation collects elements that exist in both sets. You can use the `intersection()` method or the `&` operator.

Difference:
The difference operation gets the items from one set that are not in the other set. It subtracts the elements of the second set from the first set. You can use the `difference()` method or the `-` operator.

Symmetric Difference:
Additionally, the symmetric difference is a set operation that gets the items that are in either set, but not in both. You can use the `symmetric_difference()` method or the `^` operator.