2.4. Set#

2.4.1. Python Set Manipulation: Adding, Removing, and Checking Subsets#

Sets in Python offer efficient ways to handle unique elements. Here are three essential operations:

Adding an element:

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Add a single element
fruits.add("orange")
fruits
{'apple', 'banana', 'cherry', 'orange'}

Removing an element:

fruits.remove("banana")
fruits
{'apple', 'cherry', 'orange'}

Checking for subsets:

# Check if a set is a subset
is_subset = {"apple", "cherry"}.issubset(fruits)
is_subset
True

2.4.2. Mastering Set Operations in Python: Union and Intersection#

Python sets are powerful tools for handling unique collections. Let’s explore two key operations:

Union: Combine sets to get all unique elements

# Creating a set
fruits = {"apple", "banana", "cherry"}

more_fruits = {"mango", "grape"}
all_fruits = fruits.union(more_fruits)
all_fruits
{'apple', 'banana', 'cherry', 'grape', 'mango'}

Intersection: Find common elements between sets

tropical_fruits = {"banana", "mango", "pineapple"}
common_fruits = all_fruits.intersection(tropical_fruits)
common_fruits
{'banana', 'mango'}
# Difference with another set
non_tropical_fruits = all_fruits.difference(tropical_fruits)
non_tropical_fruits
{'apple', 'cherry', 'grape'}