๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Create and use sets in Python
-
Understand set properties: unordered, unique, mutable
-
Add, remove, and loop through set items
-
Perform basic set operations like union, intersection, and difference
๐ Lesson Content
๐น What is a Set in Python?
A set is an unordered collection of unique elements.
Syntax:
โ No duplicates. Unordered. Mutable.
๐ธ Creating Sets
โ ๏ธ Use
set()
constructor to create an empty set.{}
by itself creates an empty dictionary.
๐ธ Set Characteristics
Property | Explanation |
---|---|
Unordered | No indexing โ items have no fixed position |
Unique items | Duplicates are automatically removed |
Mutable | You can add or remove items |
๐ธ Adding and Removing Items
๐ธ Looping Through a Set
โ The order of output is unpredictable due to the unordered nature of sets.
๐ธ Set Operations
Operation | Symbol or Method | Example | Description |
---|---|---|---|
Union | ` | or .union()` |
`a |
Intersection | & or .intersection() |
a & b |
Items common to both |
Difference | - or .difference() |
a - b |
Items in a but not in b |
โ Example:
๐ง Use Cases for Sets
-
Removing duplicates from a list:
-
Membership testing (
if item in set
) is very fast -
Set operations in mathematical logic or filtering
๐ Assignment
-
Create a set of 5 fruit names.
-
Add one more fruit to the set.
-
Remove one fruit using
discard()
. -
Create another set and perform:
-
Union
-
Intersection
-
Difference
-