Python | Set Operations

Python | Set Operations

In Python, Sets are a data structure that allows us to store unique values in an unordered collection. Set operations are a common way to perform various tasks with sets. In this article, we will discuss some of the most commonly used set operations in Python.

1) Union (|): This operation combines two sets into one set and returns all the distinct values from both sets.
For example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 | set2) # Output: {1, 2, 3, 4}

2) Intersection (&): This operation returns only the values that are common to both sets.
For example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 & set2) # Output: {2, 3}

3) Difference (-): This operation returns the values that are belong to one set only but not belong to another set.
For example:

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

print(set1 - set2) # Output: {1}
print(set2 - set1) # Output: {4}

4) Symmetric Difference (^): This operation returns the values that are unique to each set, but not both.
For example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1 ^ set2) # Output: {1, 4}

5) Subset (<=): This operation returns True if all elements of the first set are also present in the second set, otherwise returns False.
For example:

set1 = {1, 2}
set2 = {1, 2, 3}
print(set1 <= set2) # Output: True

6) Superset (>=): The superset operation returns True if all elements of the second set are also present in the first set, otherwise returns False.
For example:

set1 = {1, 2, 3}
set2 = {1, 2}
print(set1 >= set2) # Output: True

In conclusion, these are some of the most commonly used set operations in Python. By understanding and using these operations, we can perform various tasks with sets in a efficient manner.

Leave a Reply

Your email address will not be published.

📢 Need further clarification or have any questions? Let's connect!

Connect 1:1 With Me: Schedule Call


If you have any doubts or would like to discuss anything related to this blog, feel free to reach out to me. I'm here to help! You can schedule a call by clicking on the above given link.
I'm looking forward to hearing from you and assisting you with any inquiries you may have. Your understanding and engagement are important to me!

This will close in 20 seconds