Python program to work with mathematical set operations in python

In this tutorial, you learn to work with a set in Python. you will learn how to perform python set operations such as union, intersection, difference, and symmetric difference on sets data structure.

Set datastructure is mutable in python. you can use the built-in set() function in python to create a new set.

This program will show you how to use these powerful set operations to manipulate and analyze data, helping you to extract valuable insights and information from your datasets.

python set operations


# Take input sets from the user
set1 = set(input("Enter elements of the first set separated by space: ").split())
set2 = set(input("Enter elements of the second set separated by space: ").split())

# Perform union of the two sets
union_set = set1.union(set2)
print("Union of the sets:", union_set)

# Perform intersection of the two sets
intersection_set = set1.intersection(set2)
print("Intersection of the sets:", intersection_set)

# Perform difference of the two sets
difference_set = set1.difference(set2)
print("Difference of the sets (set1 - set2):", difference_set)

# Perform symmetric difference of the two sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric difference of the sets:", symmetric_difference_set)

Output

Enter elements of the first set separated by space: 1 2 88 99 103 78
Enter elements of the second set separated by space: 12 88 103 104 1 33
Union of the sets: {'78', '1', '12', '2', '103', '104', '99', '33', '88'}
Intersection of the sets: {'88', '103', '1'}
Difference of the sets (set1 - set2): {'2', '99', '78'}
Symmetric difference of the sets: {'2', '104', '78', '99', '12', '33'}

Conclusion

In this program, we create two sets of data by taking input from the user. and we use various set operations to perform tasks on these sets.

The union operation combines the two sets into a new set that contains all the unique elements from both sets.

The intersection operation finds the elements that are common to both sets and returns them to a new set.

The difference operation finds the elements that are in the first set but not in the second set and returns them in a new set.

Finally, the symmetric difference operation finds the elements that exist in either set, but not in both, and returns them in a new set.

These set operations can be really useful in a variety of situations. For example, you might use them to combine data from two different sources or to find the common elements in two different sets of data.

In conclusion, sets are a really powerful data structure in Python, and these set operations are a key tool in a programmer’s toolbox!

Leave a Comment