Welcome to this enlightening lesson where we’ll delve into the world of sets in Python. Sets are versatile data structures that provide a unique collection of unordered and distinct elements. In this lesson, we’ll explore the fundamentals of sets, understand their properties, and perform various set operations.

Introduction to Sets:

1. Definition:

my_set = {element1, element2, ...}

2. Creating a Set:

fruits_set = {"apple", "orange", "banana"}

3. Uniqueness of Elements:

colors_set = {"red", "green", "red", "blue"}

Set Operations:

4. Adding Elements:

my_set = {1, 2, 3}
my_set.add(4)

5. Removing Elements:

my_set = {1, 2, 3, 4}
my_set.remove(3)

6. Set Operations – Union:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)

7. Set Operations – Intersection:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)

8. Set Operations – Difference:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)

Example:

Let’s consider an example where we use sets to represent different categories of items and perform set operations:

# Example Code
fruits_set = {"apple", "orange", "banana"}
citrus_fruits = {"orange", "lemon", "grapefruit"}

# Adding a new fruit to the set
fruits_set.add("grape")

# Removing a fruit from the set
fruits_set.remove("apple")

# Union of sets
all_fruits = fruits_set.union(citrus_fruits)

# Intersection of sets
common_fruits = fruits_set.intersection(citrus_fruits)

# Difference of sets
non_citrus_fruits = fruits_set.difference(citrus_fruits)

# Displaying the results
print("All Fruits:", all_fruits)
print("Common Fruits:", common_fruits)
print("Non-Citrus Fruits:", non_citrus_fruits)

Practice Exercise:

Create a Python script that uses sets to represent the favorite colors of two individuals. Perform set operations to find the common favorite colors and the unique favorite colors of each individual.

# Example Practice Exercise
person1_colors = {"red", "green", "blue", "yellow"}
person2_colors = {"blue", "orange", "green", "purple"}

# Find common favorite colors
common_colors = person1_colors.intersection(person2_colors)

# Find unique favorite colors of each person
person1_unique_colors = person1_colors.difference(person2_colors)
person2_unique_colors = person2_colors.difference(person1_colors)

# Displaying the results
print("Common Favorite Colors:", common_colors)
print("Person 1 Unique Colors:", person1_unique_colors)
print("Person 2 Unique Colors:", person2_unique_colors)

Summary:

In this lesson, we’ve explored the fundamentals of sets in Python and performed various set operations. Sets provide a convenient way to work with unique collections of elements. Practice using sets to enhance your coding skills, and feel free to ask questions in the discussion forum. Let’s continue our Python journey with confidence in utilizing sets for different scenarios!