Python Sets – A Complete Guide for Beginners (with Examples and Output)
Python Sets – A Complete Guide for Beginners (with Examples and Output)
You have already learned about Python Lists and Python Tuples. Now it is time to learn about Sets — a unique collection that automatically removes duplicate values and comes with powerful mathematical operations like union, intersection, and difference. In this complete guide, you will learn everything about Python sets with simple examples, clear outputs, and real-life use cases at every step.
Table of Contents
- What is a Set in Python?
- How to Create a Set
- Sets Remove Duplicates Automatically
- Accessing Set Items
- Adding and Removing Items
- Important Set Methods
- Set Operations – Union, Intersection, Difference
- Set Operators (Symbols)
- Looping Through a Set
- Frozen Sets
- Set vs List vs Tuple – Full Comparison
- Real-Life Use Cases
- Practice Problems
- FAQ
1. What is a Set in Python?
A set is a collection that stores multiple values in a single variable — just like a list or tuple. But sets have three unique properties that make them completely different from the others.
Three unique properties of a set
Unordered — items have no fixed position or index
No duplicates — repeated values are removed automatically
Mutable — you can add or remove items after creation
Think of it like a real-life set
Imagine writing unique subject names on a whiteboard. If you write "Math" twice, you erase the duplicate. The order you wrote them does not matter — what matters is that each subject appears only once. That is exactly how a Python set works.
2. How to Create a Set
A set is created using curly brackets { } with items separated by commas. You can also create a set from a list using the set() function.
# Creating a set directly fruits = {"Apple", "Banana", "Mango", "Orange"} # Creating a set from a list numbers = set([10, 20, 30, 40]) # Empty set – must use set(), NOT {} empty_set = set() print(fruits) print(numbers) print(type(empty_set))
{'Orange', 'Apple', 'Mango', 'Banana'}
{40, 10, 20, 30}
<class 'set'>set() — not {}. Writing {} creates an empty dictionary, not a set. This is one of the most common beginner mistakes with sets.3. Sets Remove Duplicates Automatically
This is the most powerful and frequently used feature of sets. When you add duplicate values to a set, Python keeps only one copy and silently removes the rest. No extra code needed — it happens automatically.
# List with many duplicates marks_list = [85, 90, 85, 78, 90, 78, 92] print("List:", marks_list) # Convert to set – duplicates removed marks_set = set(marks_list) print("Set:", marks_set) print("Unique marks:", len(marks_set))
List: [85, 90, 85, 78, 90, 78, 92]
Set: {78, 85, 90, 92}
Unique marks: 4# Remove duplicates from a list – clean one-liner names = ["Rohan", "Priya", "Rohan", "Arjun", "Priya"] unique_names = list(set(names)) print(unique_names)
['Priya', 'Arjun', 'Rohan']
4. Accessing Set Items
Because sets are unordered, they do not support indexing or slicing. You cannot access an item by its position like you can with a list or tuple.
fruits = {"Apple", "Banana", "Mango"}
# This will cause a TypeError
print(fruits[0])TypeError: 'set' object is not subscriptable
To check whether an item exists in a set, use the in membership operator — which is also much faster on sets than on lists.
fruits = {"Apple", "Banana", "Mango"}
print("Apple" in fruits) # True
print("Grapes" in fruits) # False
print("Mango" not in fruits) # FalseTrue False False
in is significantly faster for sets than for lists. For a list with 1 million items, Python checks one by one. For a set, it finds the answer almost instantly using hashing.5. Adding and Removing Items
Even though sets are unordered, they are mutable — you can add new items and remove existing ones after the set is created.
Adding items
fruits = {"Apple", "Banana"}
# add() – adds a single item
fruits.add("Mango")
print(fruits)
# update() – adds multiple items from a list or another set
fruits.update(["Grapes", "Orange"])
print(fruits){'Apple', 'Banana', 'Mango'}
{'Apple', 'Banana', 'Mango', 'Grapes', 'Orange'}Removing items
fruits = {"Apple", "Banana", "Mango", "Grapes"}
# remove() – raises KeyError if item not found
fruits.remove("Banana")
print(fruits)
# discard() – no error if item not found
fruits.discard("Orange") # Orange not in set – no error
print(fruits)
# pop() – removes and returns a random item
removed = fruits.pop()
print(f"Removed: {removed}")
print(fruits)
# clear() – removes all items
fruits.clear()
print(fruits){'Apple', 'Mango', 'Grapes'}
{'Apple', 'Mango', 'Grapes'}
Removed: Apple
{'Mango', 'Grapes'}
set()discard() over remove() when you are not sure if the item exists. discard() silently does nothing if the item is not found, while remove() raises a KeyError.6. Important Set Methods
| Method | What it does | Example |
|---|---|---|
add(x) | Adds a single item to the set | s.add("hi") |
update(iter) | Adds multiple items from any iterable | s.update([1,2,3]) |
remove(x) | Removes x — raises KeyError if not found | s.remove(5) |
discard(x) | Removes x — no error if not found | s.discard(5) |
pop() | Removes and returns a random item | s.pop() |
clear() | Removes all items from the set | s.clear() |
copy() | Returns a copy of the set | s2 = s.copy() |
union(s2) | Returns all items from both sets | s.union(s2) |
intersection(s2) | Returns only common items | s.intersection(s2) |
difference(s2) | Returns items in s but not in s2 | s.difference(s2) |
issubset(s2) | True if all items of s are in s2 | s.issubset(s2) |
issuperset(s2) | True if s contains all items of s2 | s.issuperset(s2) |
7. Set Operations – Union, Intersection, Difference
This is the most powerful feature of sets — performing mathematical operations between two sets. These operations come directly from Set Theory in mathematics. If you have studied Venn diagrams in school, these will feel very familiar.
{1,2,3,4}
{3,4,5,6}
Union – all items from both sets
Union combines every item from both sets, removing duplicates automatically.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A.union(B)
print("Union:", result)Union: {1, 2, 3, 4, 5, 6}Intersection – only common items
Intersection returns only the items that exist in both sets.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A.intersection(B)
print("Intersection:", result)Intersection: {3, 4}Difference – items in A but not in B
Difference returns items that are in the first set but not in the second.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("A - B:", A.difference(B)) # In A, not in B
print("B - A:", B.difference(A)) # In B, not in AA - B: {1, 2}
B - A: {5, 6}Symmetric Difference – items not common to both
Symmetric difference returns items that are in either set, but not in both — the opposite of intersection.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A.symmetric_difference(B)
print("Symmetric Difference:", result)Symmetric Difference: {1, 2, 5, 6}8. Set Operators (Symbols)
Python also lets you perform set operations using operator symbols — a shorter alternative to calling methods.
| Operation | Method | Operator | Example |
|---|---|---|---|
| Union | union() | | | A | B |
| Intersection | intersection() | & | A & B |
| Difference | difference() | - | A - B |
| Symmetric Diff | symmetric_difference() | ^ | A ^ B |
| Subset check | issubset() | <= | A <= B |
| Superset check | issuperset() | >= | A >= B |
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print("Union: ", A | B)
print("Intersection: ", A & B)
print("Difference: ", A - B)
print("Sym. Diff: ", A ^ B)Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
Sym. Diff: {1, 2, 5, 6}9. Looping Through a Set
You can use a for loop to go through every item in a set. Remember — the order is not guaranteed, so you may see items in a different order each time you run the program.
fruits = {"Apple", "Banana", "Mango", "Orange"}
for fruit in fruits:
print(fruit)Orange Apple Mango Banana
Using set with if condition inside loop
marks = {85, 42, 90, 35, 78, 60}
print("Passing marks:")
for m in marks:
if m >= 40:
print(m)Passing marks: 85 90 78 60 42
10. Frozen Sets
A frozenset is an immutable version of a set. Once created, you cannot add or remove items — similar to how a tuple is an immutable version of a list. Frozensets can be used as dictionary keys because they are hashable.
fs = frozenset([1, 2, 3, 4]) print(fs) print(type(fs)) # All read operations work print(3 in fs) # True print(len(fs)) # 4 # Trying to modify raises an error fs.add(5)
frozenset({1, 2, 3, 4})
<class 'frozenset'>
True
4
AttributeError: 'frozenset' object has no attribute 'add'frozenset when you need all the benefits of a set (fast membership check, no duplicates) but you want to make sure the data cannot be accidentally changed.11. Set vs List vs Tuple – Full Comparison
Now that you have learned all three — lists, tuples, and sets — here is a complete comparison to help you choose the right one for any situation.
| Feature | List [ ] | Tuple ( ) | Set { } |
|---|---|---|---|
| Ordered? | Yes | Yes | No |
| Allows duplicates? | Yes | Yes | No – auto removed |
| Mutable? | Yes | No | Yes |
| Indexing? | Yes | Yes | No |
| Slicing? | Yes | Yes | No |
| Can be dict key? | No | Yes | No |
| Mathematical ops? | No | No | Yes – union, intersection |
| Speed (membership check) | Slow (O(n)) | Slow (O(n)) | Very fast (O(1)) |
| Best used for | Ordered, changeable data | Fixed, protected data | Unique values, fast lookup |
12. Real-Life Use Cases
Use case 1 – Remove duplicates from student list
registered = ["Rohan", "Priya", "Rohan", "Arjun", "Priya", "Meera"] unique_students = list(set(registered)) print(f"Total registrations: {len(registered)}") print(f"Unique students: {len(unique_students)}") print(unique_students)
Total registrations: 6 Unique students: 4 ['Meera', 'Rohan', 'Arjun', 'Priya']
Use case 2 – Find common subjects between two students
rohan_subjects = {"Math", "Science", "English", "Hindi"}
priya_subjects = {"Math", "English", "Computer", "Art"}
common = rohan_subjects & priya_subjects
only_rohan = rohan_subjects - priya_subjects
only_priya = priya_subjects - rohan_subjects
all_subjects = rohan_subjects | priya_subjects
print(f"Common subjects: {common}")
print(f"Only Rohan studies: {only_rohan}")
print(f"Only Priya studies: {only_priya}")
print(f"All subjects: {all_subjects}")Common subjects: {'Math', 'English'}
Only Rohan studies: {'Science', 'Hindi'}
Only Priya studies: {'Computer', 'Art'}
All subjects: {'Math', 'English', 'Science', 'Hindi', 'Computer', 'Art'}Use case 3 – Fast membership check
banned_users = {"spam_user", "bot123", "fake_acc", "abuse_01"}
username = input("Enter username: ")
if username in banned_users:
print("Access denied. This account is banned.")
else:
print(f"Welcome, {username}!")Enter username: rohan Welcome, rohan!
13. Practice Problems
Try solving these problems using what you learned in this post and from the Python Lists, Python Loops, and Python Operators posts.
Basic set operations
- Create a set of 5 fruits
- Add two new items using add()
- Remove an item using discard()
- Check if an item exists using in
- Create an empty set correctly
Duplicates and conversion
- Remove duplicates from a list of numbers
- Remove duplicates from a list of names
- Count unique words in a sentence
- Convert a set back to a sorted list
- Find total unique items in two lists combined
Set operations
- Find union of two sets
- Find common items in two sets
- Find items in A but not in B
- Find symmetric difference
- Check if one set is a subset of another
Real-life challenges
- Find students who passed both subjects
- Find subjects studied by only one student
- Build a banned words checker
- Find unique visitors from a log list
- Compare two shopping carts for common items
- A set stores multiple values using curly brackets
{ } - Sets are unordered, mutable, and do not allow duplicate values
- Use
set()to create an empty set —{}creates a dictionary - Sets automatically remove duplicate values — perfect for deduplication
- No indexing or slicing — use
into check membership add()adds one item,update()adds multiple items- Use
discard()overremove()to avoid KeyError - Set operations: union (
|), intersection (&), difference (-), symmetric difference (^) - A
frozensetis an immutable set — cannot be changed after creation - Sets are the fastest collection for membership checking in Python
Frequently Asked Questions (FAQ)
Q1. What is the main difference between a set and a list in Python?
A list is ordered and allows duplicates — items keep their position and the same value can appear multiple times. A set is unordered and does not allow duplicates — it automatically removes repeated values and items have no fixed position.
Q2. Why can I not access a set item using an index?
Sets are unordered — items do not have a fixed position. Since there is no guaranteed order, there is no meaningful index to use. To access items, loop through the set with a for loop or check membership using in.
Q3. What is the difference between remove() and discard() in Python sets?
Both remove a specified item from the set. The difference is error handling — remove() raises a KeyError if the item does not exist, while discard() does nothing and raises no error. Always use discard() when you are unsure whether the item is in the set.
Q4. Can a Python set contain different data types?
Yes, but only hashable types. A set can contain integers, floats, strings, and tuples. It cannot contain lists, dictionaries, or other sets because they are mutable and therefore unhashable.
Q5. What is a frozenset and when should I use it?
A frozenset is an immutable version of a set. Once created, items cannot be added or removed. Use a frozenset when you need the unique-value and fast-lookup benefits of a set, but you want to ensure the data is never accidentally changed — similar to using a tuple instead of a list.
Q6. How is set union different from set update?
union() returns a new set containing all items from both sets — the original sets are unchanged. update() modifies the original set by adding all items from another iterable to it in place. Use union() when you want a new result, use update() when you want to modify the existing set.
Found this post helpful? Share it with someone learning Python. Drop your practice solutions in the comments — happy to review them!
"A set in Python is like a promise — no repetitions, no order, just pure unique values."
Comments
Post a Comment