Welcome to our comprehensive guide on Set Operations in Python! This tutorial is designed to help you understand and master this essential topic, whether you're a beginner or an intermediate learner. Let's dive in!
In Python, a set is an unordered collection of unique elements. Sets are useful when you want to work with multiple items but don't care about the order. They are often used to eliminate duplicates and perform various operations on collections.
# Creating a set
my_set = {"apple", "banana", "cherry", "apple"} # Notice the duplicated 'apple' is removedPython provides several built-in functions to perform operations on sets. Here are the most common ones:
union()) 💡The union() function returns a new set that contains all elements from both sets. It merges the sets without duplicates.
# Creating two sets
set1 = {"a", "b", "c"}
set2 = {"c", "d", "e"}
# Finding union
union_set = set1.union(set2)
print(union_set) # Output: {'a', 'b', 'c', 'd', 'e'}intersection()) 💡The intersection() function returns a new set that contains only the elements common to both sets.
# Finding intersection
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {'c'}difference()) 💡The difference() function returns a new set that contains all elements from the calling set that are not in the other set.
# Finding difference
diff_set1 = set1.difference(set2)
diff_set2 = set2.difference(set1)
print("Set1 difference:", diff_set1) # Output: {'a', 'b'}
print("Set2 difference:", diff_set2) # Output: {'d', 'e'}symmetric_difference()) 💡The symmetric_difference() function returns a new set that contains the elements present in either of the sets but not in both.
# Finding symmetric difference
sym_diff_set = set1.symmetric_difference(set2)
print(sym_diff_set) # Output: {'a', 'b', 'd', 'e'}Which set operation will give you the elements present in either of the sets but not in both?
That's all for now! In the next lesson, we'll dive deeper into sets and explore more advanced topics. Happy coding! 💡💡💡