8.4. Sets (basics)
Table of Contents
What is a Set?
In Python, a set is an unordered collection of unique elements.
Key properties:
- No duplicates: If you add the same value twice, it appears only once.
- Unordered: A set does not keep the order of items; you can’t rely on positions (no indexing like
my_set[0]). - Mutable: You can add or remove elements from a set after creating it.
- Elements must be hashable: In practice, you usually store numbers, strings, or tuples in sets (not lists or other sets).
Typical uses:
- Removing duplicates from a list.
- Checking if something is a member of a collection, very efficiently.
- Doing math-like operations such as union and intersection (e.g. “items that are in both groups”).
Creating Sets
Using curly braces
You can create a set using {} with comma-separated values:
fruits = {"apple", "banana", "cherry"}
print(fruits)Remember: the order of printing may be different from how you wrote it.
Using the `set()` function
You can also create a set using the set() function:
numbers = set([1, 2, 3])
print(numbers)This is especially useful for converting other collections:
- From list to set:
nums_list = [1, 2, 2, 3, 3, 3]
nums_set = set(nums_list)
print(nums_set) # duplicates removed- From string to set (characters):
letters = set("hello")
print(letters) # each unique character onceEmpty set
Be careful: {} creates an empty dictionary, not a set.
To create an empty set, use:
empty_set = set()
print(empty_set)Uniqueness and Duplicates
Sets automatically remove duplicates:
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3}If you add the same element multiple times, it only appears once:
colors = set()
colors.add("red")
colors.add("red")
colors.add("blue")
print(colors) # {"red", "blue"}You can use this property to quickly remove duplicates from a list:
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = set(names)
print(unique_names)If you need a list again, convert it back:
unique_names_list = list(unique_names)
print(unique_names_list)Basic Set Operations
Membership: checking if something is in a set
Use the in and not in operators:
animals = {"cat", "dog", "bird"}
print("cat" in animals) # True
print("fish" in animals) # False
print("fish" not in animals) # TrueMembership checks in sets are typically faster than in lists, especially when the collection is large.
Adding elements: `add()`
Use add() to insert a single element:
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)If the element already exists, nothing changes:
numbers.add(3) # 3 is already in the set
print(numbers) # still {1, 2, 3, 4}Removing elements: `remove()` and `discard()`
remove(x)removesx, but causes an error ifxis not in the set.discard(x)removesxif present, and does nothing ifxis absent.
numbers = {1, 2, 3}
numbers.remove(2)
print(numbers) # {1, 3}
numbers.discard(5) # 5 is not in the set, but no error
print(numbers) # still {1, 3}
If you’re unsure whether an element is present, discard() is safer.
Removing and returning an element: `pop()`
pop() removes and returns some element from the set. Since sets are unordered, you don’t control which one:
items = {"apple", "banana", "cherry"}
item = items.pop()
print("Popped:", item)
print("Remaining:", items)Clearing all elements: `clear()`
To empty a set:
data = {1, 2, 3}
data.clear()
print(data) # set()Set Operations (Like Math Sets)
Sets support operations similar to mathematical sets.
Given:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}Union: `|` or `union()`
Union combines elements that are in either set.
$$
A \cup B = \{x : x \in A \text{ or } x \in B\}
$$
In Python:
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b)) # same resultIntersection: `&` or `intersection()`
Intersection keeps elements that are in both sets.
$$
A \cap B = \{x : x \in A \text{ and } x \in B\}
$$
In Python:
print(a & b) # {3, 4}
print(a.intersection(b)) # same resultDifference: `-` or `difference()`
Difference keeps elements that are in the first set but not in the second.
$$
A \setminus B = \{x : x \in A \text{ and } x \notin B\}
$$
In Python:
print(a - b) # {1, 2}
print(b - a) # {5, 6}
print(a.difference(b)) # {1, 2}Symmetric difference: `^` or `symmetric_difference()`
Symmetric difference keeps elements that are in either set, but not in both.
$$
A \triangle B = (A \cup B) \setminus (A \cap B)
$$
In Python:
print(a ^ b) # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # same resultSubsets and Supersets (Basics)
For simple checks of “is everything in this set also in that set?” you can use:
<=(subset)>=(superset)
Example:
small = {1, 2}
big = {1, 2, 3, 4}
print(small <= big) # True: small is a subset of big
print(big >= small) # True: big is a superset of smallWhen to Use Sets (Practical Ideas)
Some beginner-friendly scenarios:
- Remove duplicates from data:
emails = ["a@example.com", "b@example.com", "a@example.com"]
unique_emails = set(emails)- Fast membership checks (e.g. words you want to ignore):
stop_words = {"the", "and", "is", "of"}
word = "and"
if word in stop_words:
print("Skip this word")- Comparing groups (e.g. students in different classes):
class_a = {"Alice", "Bob", "Carol"}
class_b = {"Bob", "Dave"}
both = class_a & class_b # in both classes
only_a = class_a - class_b # only in class A
everyone = class_a | class_b # all unique studentsLimitations and Things to Remember
- Sets are unordered: you cannot rely on item order, and you cannot use indexes like
my_set[0]. - Set elements must be immutable (e.g. numbers, strings, tuples are fine; lists are not).
- There is a separate type called
frozenset(an immutable set), but that goes beyond the basics.
Understanding these basics will help you decide when a set is more appropriate than a list, tuple, or dictionary in your programs.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!