Lesson 5.3: Sets – Basics and Operations
Introduction:
Sets are unordered collections of unique elements in Python. They are useful for eliminating duplicates, performing mathematical set operations, and quickly checking membership. Understanding sets is essential for data analysis, filtering, and managing collections efficiently.
1. Creating Sets:
-
Sets are created using curly braces
{}or theset()function.
Examples:
2. Accessing Elements:
-
Sets are unordered, so elements cannot be accessed using an index.
-
You can iterate over a set using a loop.
Example:
3. Adding and Removing Elements:
-
add()– Adds a single element -
update()– Adds multiple elements -
remove()– Removes a specific element (raises error if not found) -
discard()– Removes an element (does not raise error if not found) -
pop()– Removes and returns an arbitrary element
Example:
4. Set Operations:
-
Union (
|or union()) – Combine two sets -
Intersection (
&or intersection()) – Common elements -
Difference (
-or difference()) – Elements in one set but not the other -
Symmetric Difference (
^or symmetric_difference()) – Elements in either set but not both
Example:
Practical Tips:
-
Use sets to remove duplicates from lists
-
Sets are unordered; indexing is not possible
-
Ideal for membership testing and mathematical operations
Learning Outcome of This Lesson:
-
Understand the basics of sets and their uniqueness property
-
Create and modify sets efficiently
-
Perform common set operations like union, intersection, and difference
-
Use sets in real-world scenarios to handle collections of data
