Python Tutorial: Set Operations 🎯

beginner
9 min

Python Tutorial: Set Operations 🎯

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!

What are Sets? 📝

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.

python
# Creating a set my_set = {"apple", "banana", "cherry", "apple"} # Notice the duplicated 'apple' is removed

Set Operations 💡

Python provides several built-in functions to perform operations on sets. Here are the most common ones:

1. Union (union()) 💡

The union() function returns a new set that contains all elements from both sets. It merges the sets without duplicates.

python
# 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'}

2. Intersection (intersection()) 💡

The intersection() function returns a new set that contains only the elements common to both sets.

python
# Finding intersection intersection_set = set1.intersection(set2) print(intersection_set) # Output: {'c'}

3. Difference (difference()) 💡

The difference() function returns a new set that contains all elements from the calling set that are not in the other set.

python
# 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'}

4. Symmetric Difference (symmetric_difference()) 💡

The symmetric_difference() function returns a new set that contains the elements present in either of the sets but not in both.

python
# Finding symmetric difference sym_diff_set = set1.symmetric_difference(set2) print(sym_diff_set) # Output: {'a', 'b', 'd', 'e'}

Quiz Time! 💡

Quick Quiz
Question 1 of 1

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! 💡💡💡