Python Sets Tutorial
Quick Answer
Sets explains sets are a fundamental data structure in Python used to store unique elements.
Learning Objectives
- Explain the purpose of Sets in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Sets.
- Apply Sets in a simple real-world scenario or practice task.
Introduction
Sets are a fundamental data structure in Python used to store unique elements.
They are unordered collections that support mathematical set operations like union, intersection, and difference.
Sets are powerful for handling unique data and performing mathematical set operations efficiently.
What is a Set in Python?
A set is an unordered collection of unique elements in Python.
Unlike lists or tuples, sets do not allow duplicate values and do not maintain any order.
- Defined using curly braces {} or the set() constructor.
- Elements must be immutable types like numbers, strings, or tuples.
- Duplicates are automatically removed.
Creating Sets
You can create sets by enclosing comma-separated values in curly braces or by using the set() function.
Empty sets must be created with set() because {} creates an empty dictionary.
- Example: my_set = {1, 2, 3}
- Example: my_set = set([1, 2, 3])
Basic Set Operations
Python sets support common mathematical operations such as union, intersection, difference, and symmetric difference.
These operations help in comparing and combining sets efficiently.
- Union (|): Combines elements from both sets.
- Intersection (&): Elements common to both sets.
- Difference (-): Elements in one set but not the other.
- Symmetric Difference (^): Elements in either set but not both.
Modifying Sets
Sets are mutable, so you can add or remove elements after creation.
Common methods include add(), remove(), discard(), and pop().
- add(element): Adds an element to the set.
- remove(element): Removes an element; raises KeyError if not found.
- discard(element): Removes an element if present; no error if absent.
- pop(): Removes and returns an arbitrary element.
Use Cases for Sets
Sets are ideal when you need to ensure uniqueness or perform membership tests quickly.
They are commonly used in data cleaning, removing duplicates, and set theory problems.
- Removing duplicates from a list.
- Checking if an element exists in a collection.
- Performing mathematical set operations.
Practical Example
This example shows how to create a set, add an element, and remove an element.
This example demonstrates union, intersection, difference, and symmetric difference operations on sets.
Examples
my_set = {1, 2, 3, 4}
print(my_set)
my_set.add(5)
print(my_set)
my_set.remove(2)
print(my_set)This example shows how to create a set, add an element, and remove an element.
a = {1, 2, 3}
b = {3, 4, 5}
print('Union:', a | b)
print('Intersection:', a & b)
print('Difference:', a - b)
print('Symmetric Difference:', a ^ b)This example demonstrates union, intersection, difference, and symmetric difference operations on sets.
Best Practices
- Use sets when you need to store unique items and order does not matter.
- Prefer discard() over remove() when you are unsure if the element exists to avoid errors.
- Use set operations for efficient membership and comparison tasks.
- Remember that set elements must be immutable types.
Common Mistakes
- Trying to create an empty set with {} which creates an empty dictionary instead.
- Using mutable types like lists as set elements, which raises a TypeError.
- Assuming sets maintain insertion order (they do not).
- Using remove() without checking if the element exists, causing KeyError.
Hands-on Exercise
Remove Duplicates from a List
Write a Python function that takes a list with duplicate elements and returns a list with duplicates removed using sets.
Expected output: [1, 2, 3] for input [1, 2, 2, 3, 1]
Hint: Convert the list to a set and then back to a list.
Set Operations Practice
Given two sets, write code to find their union, intersection, difference, and symmetric difference.
Expected output: Correct sets printed for each operation.
Hint: Use the operators |, &, -, and ^ respectively.
Interview Questions
What is a set in Python and how is it different from a list?
InterviewA set is an unordered collection of unique elements, whereas a list is ordered and can contain duplicates.
How do you create an empty set in Python?
InterviewUse set() to create an empty set. Using {} creates an empty dictionary.
Can you store mutable elements like lists inside a set?
InterviewNo, set elements must be immutable types because sets rely on hashable elements.
MCQ Quiz
1. Which of the following statements about Python sets is TRUE?
Select one option to check your answer.
2. What will be the result of the following code? my_set = {1, 2, 2, 3} print(my_set)
Select one option to check your answer.
3. Which set operation returns elements that are in either of the two sets but not in both?
Select one option to check your answer.
Key Takeaways
- Sets are a fundamental data structure in Python used to store unique elements.
- They are unordered collections that support mathematical set operations like union, intersection, and difference.
- A set is an unordered collection of unique elements in Python.
- Unlike lists or tuples, sets do not allow duplicate values and do not maintain any order.
- You can create sets by enclosing comma-separated values in curly braces or by using the set() function.
Frequently Asked Questions
How do sets handle duplicate elements?
Sets automatically remove duplicates; only unique elements are stored.
Are sets ordered in Python?
No, sets are unordered collections and do not maintain element order.
Can I use a list as an element of a set?
No, because lists are mutable and unhashable, they cannot be elements of a set.
Summary
Python sets are unordered collections of unique, immutable elements.
They support efficient membership testing and mathematical set operations.
Sets are mutable and provide methods to add and remove elements.
Using sets can simplify tasks involving uniqueness and set theory.





