Python Sets – A Complete Guide for Beginners (with Examples and Output)

 

 Python Sets – A Complete Guide for Beginners (with Examples and Output)

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~14 min

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

  1. What is a Set in Python?
  2. How to Create a Set
  3. Sets Remove Duplicates Automatically
  4. Accessing Set Items
  5. Adding and Removing Items
  6. Important Set Methods
  7. Set Operations – Union, Intersection, Difference
  8. Set Operators (Symbols)
  9. Looping Through a Set
  10. Frozen Sets
  11. Set vs List vs Tuple – Full Comparison
  12. Real-Life Use Cases
  13. Practice Problems
  14. FAQ

1. What is a Set in Python?

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'>
To create an empty set, you must use set() — not {}. Writing {} creates an empty dictionary, not a set. This is one of the most common beginner mistakes with sets.
Notice the output order is different from the input order. This is because sets are unordered — Python does not guarantee any specific order for set items. The order may even change each time you run the program.

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']
Converting a list to a set and back to a list is the fastest and most Pythonic way to remove duplicates. This is a very common technique asked in Python coding interviews.

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)  # False
True
False
False
Checking membership with 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()
Always prefer 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

MethodWhat it doesExample
add(x)Adds a single item to the sets.add("hi")
update(iter)Adds multiple items from any iterables.update([1,2,3])
remove(x)Removes x — raises KeyError if not founds.remove(5)
discard(x)Removes x — no error if not founds.discard(5)
pop()Removes and returns a random items.pop()
clear()Removes all items from the sets.clear()
copy()Returns a copy of the sets2 = s.copy()
union(s2)Returns all items from both setss.union(s2)
intersection(s2)Returns only common itemss.intersection(s2)
difference(s2)Returns items in s but not in s2s.difference(s2)
issubset(s2)True if all items of s are in s2s.issubset(s2)
issuperset(s2)True if s contains all items of s2s.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.

Set A
{1,2,3,4}
Set B
{3,4,5,6}
Common items {3,4} are in the overlapping region

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 A
A - 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}
Easy way to remember: Union = everything. Intersection = only shared. Difference = one side only. Symmetric difference = everything except the shared part.

8. Set Operators (Symbols)

Python also lets you perform set operations using operator symbols — a shorter alternative to calling methods.

OperationMethodOperatorExample
Unionunion()|A | B
Intersectionintersection()&A & B
Differencedifference()-A - B
Symmetric Diffsymmetric_difference()^A ^ B
Subset checkissubset()<=A <= B
Superset checkissuperset()>=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
The output order may be different from what you expect. Sets do not preserve insertion order. If order matters to you, use a list or tuple instead.

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

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'
Use a 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 — liststuples, and sets — here is a complete comparison to help you choose the right one for any situation.

FeatureList [ ]Tuple ( )Set { }
Ordered?YesYesNo
Allows duplicates?YesYesNo – auto removed
Mutable?YesNoYes
Indexing?YesYesNo
Slicing?YesYesNo
Can be dict key?NoYesNo
Mathematical ops?NoNoYes – union, intersection
Speed (membership check)Slow (O(n))Slow (O(n))Very fast (O(1))
Best used forOrdered, changeable dataFixed, protected dataUnique 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 ListsPython Loops, and Python Operators posts.

Basic set operations

  1. Create a set of 5 fruits
  2. Add two new items using add()
  3. Remove an item using discard()
  4. Check if an item exists using in
  5. Create an empty set correctly

Duplicates and conversion

  1. Remove duplicates from a list of numbers
  2. Remove duplicates from a list of names
  3. Count unique words in a sentence
  4. Convert a set back to a sorted list
  5. Find total unique items in two lists combined

Set operations

  1. Find union of two sets
  2. Find common items in two sets
  3. Find items in A but not in B
  4. Find symmetric difference
  5. Check if one set is a subset of another

Real-life challenges

  1. Find students who passed both subjects
  2. Find subjects studied by only one student
  3. Build a banned words checker
  4. Find unique visitors from a log list
  5. Compare two shopping carts for common items
Try each problem on your own before looking for hints. Post your solutions in the comments — let's learn and grow together!

Quick Summary – What You Learned
  • 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 in to check membership
  • add() adds one item, update() adds multiple items
  • Use discard() over remove() to avoid KeyError
  • Set operations: union (|), intersection (&), difference (-), symmetric difference (^)
  • frozenset is 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?

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

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Loops Explained – for Loop and while Loop with Examples and Output