Python Sets: Complete Guide with Examples
A set in Python is a mutable collection used to store unique elements. Unlike lists and tuples, sets do not maintain elements using numeric indexes.
Sets are especially useful when you need to:
- Remove duplicate values
- Perform mathematical set operations
- Compare two collections
- Check whether an element exists
- Find common or different elements between collections
A set can be created using curly braces {}:
1fruits = {"Apple", "Banana", "Orange"} 2 3print(fruits)
Possible output:
1{'Banana', 'Orange', 'Apple'}
The order may be different when you run the program.
Important: A set is unordered, so you should not rely on the order in which elements are displayed or iterated.
Why Use Sets in Python?
Consider a list containing duplicate values:
1numbers = [10, 20, 20, 30, 30, 40] 2 3unique_numbers = set(numbers) 4 5print(unique_numbers)
Output:
1{10, 20, 30, 40}
The set() constructor automatically removes duplicate values.
Sets are particularly useful for operations such as:
1Unique values 2 ↓ 3Membership checking 4 ↓ 5Union 6 ↓ 7Intersection 8 ↓ 9Difference 10 ↓ 11Symmetric difference
For example, suppose you want to find skills shared by two developers:
1developer_a = {"Python", "Django", "SQL"} 2developer_b = {"Python", "Docker", "SQL"} 3 4common_skills = developer_a & developer_b 5 6print(common_skills)
Output:
1{'Python', 'SQL'}
Important Features of Python Sets
Python sets have several important characteristics:
- Sets store unique elements.
- Sets are mutable.
- Sets are unordered.
- Sets do not support numeric indexing.
- Sets support membership testing with
in. - Sets support mathematical set operations.
- Sets can contain different hashable data types.
- Sets can be modified using methods such as
add()andremove(). - Set elements must be hashable.
- A set cannot contain a list or another mutable set.
For example, this is valid:
1data = {"Python", 100, 5.5, True} 2 3print(data)
But this is invalid because a list is not hashable:
1data = {["Python", "Java"]}
Python raises:
1TypeError: unhashable type: 'list'
Creating a Set
The simplest way to create a set is with curly braces:
1colors = {"Red", "Green", "Blue"} 2 3print(colors)
Possible output:
1{'Red', 'Green', 'Blue'}
Remember that the output order is not guaranteed.
Creating an Empty Set
There is an important difference between {} and set().
This creates an empty dictionary:
1data = {} 2 3print(type(data))
Output:
1<class 'dict'>
To create an empty set, use set():
1data = set() 2 3print(type(data))
Output:
1<class 'set'>
This is one of the most common Python set mistakes for beginners.
Creating a Set from a List
You can convert a list into a set using set().
1numbers = [1, 2, 2, 3, 4, 4] 2 3unique_numbers = set(numbers) 4 5print(unique_numbers)
Output:
1{1, 2, 3, 4}
This is one of the easiest ways to remove duplicate values.
Creating a Set from a String
Strings are iterable, so you can create a set containing their unique characters.
1word = "programming" 2 3letters = set(word) 4 5print(letters)
The output may appear in a different order:
1{'p', 'r', 'o', 'g', 'a', 'm', 'i', 'n'}
Repeated characters such as m, g, and r appear only once.
Duplicate Values in Sets
Sets automatically eliminate duplicate values.
1numbers = {1, 2, 2, 3, 3, 4, 4, 5} 2 3print(numbers)
Output:
1{1, 2, 3, 4, 5}
Another example:
1names = {"Ankit", "Rahul", "Ankit", "Aman"} 2 3print(names)
Possible output:
1{'Rahul', 'Ankit', 'Aman'}
The duplicate "Ankit" is stored only once.
Membership Testing
Sets are particularly useful for checking whether an element exists.
Use the in operator:
1fruits = {"Apple", "Banana", "Orange"} 2 3print("Apple" in fruits) 4print("Mango" in fruits)
Output:
1True 2False
You can also use not in:
1fruits = {"Apple", "Banana", "Orange"} 2 3if "Mango" not in fruits: 4 print("Mango is not available")
Output:
1Mango is not available
Set membership testing is generally very efficient because Python sets are implemented using hash tables.
Finding the Length of a Set
Use len() to find the number of elements.
1numbers = {10, 20, 30, 40} 2 3print(len(numbers))
Output:
14
Because duplicate values are removed, the length represents the number of unique elements.
1numbers = {10, 10, 20, 20, 30} 2 3print(len(numbers))
Output:
13
Adding Elements with add()
The add() method adds one element to a set.
1fruits = {"Apple", "Banana"} 2 3fruits.add("Orange") 4 5print(fruits)
Possible output:
1{'Apple', 'Banana', 'Orange'}
If the element already exists, nothing changes:
1fruits = {"Apple", "Banana", "Orange"} 2 3fruits.add("Apple") 4 5print(fruits)
Output:
1{'Apple', 'Banana', 'Orange'}
A set never creates duplicate elements.
Removing Elements with remove()
The remove() method removes a specific element.
1fruits = {"Apple", "Banana", "Orange"} 2 3fruits.remove("Banana") 4 5print(fruits)
Possible output:
1{'Apple', 'Orange'}
If the element does not exist, remove() raises a KeyError:
1fruits = {"Apple", "Banana"} 2 3fruits.remove("Mango")
Error:
1KeyError: 'Mango'
Removing Elements Safely with discard()
The discard() method is similar to remove(), but it does not raise an error when the element is missing.
1fruits = {"Apple", "Banana"} 2 3fruits.discard("Mango") 4 5print(fruits)
Output:
1{'Apple', 'Banana'}
Use discard() when you do not care whether the value exists before attempting to remove it.
Adding Multiple Elements with update()
The update() method adds multiple elements to a set.
1fruits = {"Apple", "Banana"} 2 3fruits.update({"Orange", "Mango"}) 4 5print(fruits)
Possible output:
1{'Apple', 'Banana', 'Orange', 'Mango'}
You can also provide a list:
1numbers = {1, 2} 2 3numbers.update([3, 4, 5]) 4 5print(numbers)
Output:
1{1, 2, 3, 4, 5}
You can update a set using many iterable objects:
1numbers = {1, 2} 2 3numbers.update((3, 4)) 4numbers.update([5, 6]) 5 6print(numbers)
Output:
1{1, 2, 3, 4, 5, 6}
Removing All Elements with clear()
The clear() method removes every element from a set.
1numbers = {1, 2, 3, 4} 2 3numbers.clear() 4 5print(numbers)
Output:
1set()
The variable still refers to a set; the set is simply empty.
Removing an Arbitrary Element with pop()
The pop() method removes and returns an arbitrary element.
1colors = {"Red", "Green", "Blue"} 2 3removed_color = colors.pop() 4 5print("Removed:", removed_color) 6print("Remaining:", colors)
The removed value is not predictable.
Important: Do not use
pop()when you need to remove a specific value. Useremove()ordiscard()instead.
Copying a Set
The copy() method creates a shallow copy of a set.
1original = {1, 2, 3} 2 3copy_of_set = original.copy() 4 5print(copy_of_set)
Output:
1{1, 2, 3}
Changes to the copied set do not change the original set:
1original = {1, 2, 3} 2 3copy_of_set = original.copy() 4copy_of_set.add(4) 5 6print("Original:", original) 7print("Copy:", copy_of_set)
Output:
1Original: {1, 2, 3} 2Copy: {1, 2, 3, 4}
Set Union
The union of two sets contains all unique elements from both sets.
You can use the union() method:
1set_a = {1, 2, 3} 2set_b = {3, 4, 5} 3 4result = set_a.union(set_b) 5 6print(result)
Output:
1{1, 2, 3, 4, 5}
You can also use the | operator:
1result = set_a | set_b 2 3print(result)
Output:
1{1, 2, 3, 4, 5}
Real-World Union Example
Suppose two developers have different technical skills:
1frontend = {"HTML", "CSS", "JavaScript"} 2backend = {"Python", "JavaScript", "Django"} 3 4all_skills = frontend | backend 5 6print(all_skills)
Possible output:
1{'HTML', 'CSS', 'JavaScript', 'Python', 'Django'}
The duplicate "JavaScript" appears only once.
Set Intersection
The intersection contains elements that exist in both sets.
1set_a = {1, 2, 3} 2set_b = {2, 3, 4} 3 4result = set_a.intersection(set_b) 5 6print(result)
Output:
1{2, 3}
The & operator provides a shorter syntax:
1result = set_a & set_b 2 3print(result)
Output:
1{2, 3}
Real-World Intersection Example
Suppose two students are enrolled in different subjects:
1student_a = {"Math", "Science", "English"} 2student_b = {"Science", "Computer", "English"} 3 4common_subjects = student_a & student_b 5 6print(common_subjects)
Possible output:
1{'Science', 'English'}
This allows you to quickly find subjects shared by both students.
Set Difference
The difference returns elements that exist in the first set but not in the second.
1set_a = {1, 2, 3} 2set_b = {2, 3, 4} 3 4result = set_a.difference(set_b) 5 6print(result)
Output:
1{1}
The - operator can also be used:
1result = set_a - set_b 2 3print(result)
Output:
1{1}
The order matters.
1print(set_a - set_b) 2print(set_b - set_a)
Output:
1{1} 2{4}
Real-World Difference Example
Suppose a company requires several skills and a candidate has some of them:
1required_skills = {"Python", "SQL", "Git", "Docker"} 2candidate_skills = {"Python", "Git"} 3 4missing_skills = required_skills - candidate_skills 5 6print(missing_skills)
Possible output:
1{'SQL', 'Docker'}
This is a practical example of using set difference to find missing skills.
Symmetric Difference
The symmetric difference returns elements that exist in either set, but not in both.
1set_a = {1, 2, 3} 2set_b = {3, 4, 5} 3 4result = set_a.symmetric_difference(set_b) 5 6print(result)
Output:
1{1, 2, 4, 5}
The ^ operator provides the same operation:
1result = set_a ^ set_b 2 3print(result)
Output:
1{1, 2, 4, 5}
Real-World Example
1team_a = {"Ankit", "Rahul"} 2team_b = {"Rahul", "Aman"} 3 4different_members = team_a ^ team_b 5 6print(different_members)
Possible output:
1{'Ankit', 'Aman'}
Rahul is excluded because he belongs to both teams.
Set Comparison
Python provides methods for checking relationships between sets.
issubset()
A set is a subset if every element in it exists in another set.
1required = {"Python", "SQL"} 2skills = {"Python", "SQL", "Docker", "Git"} 3 4print(required.issubset(skills))
Output:
1True
You can also use <=:
1print(required <= skills)
Output:
1True
issuperset()
A set is a superset if it contains every element of another set.
1skills = {"Python", "SQL", "Docker", "Git"} 2required = {"Python", "SQL"} 3 4print(skills.issuperset(required))
Output:
1True
You can also use >=:
1print(skills >= required)
isdisjoint()
Two sets are disjoint when they have no elements in common.
1set_a = {1, 2, 3} 2set_b = {4, 5, 6} 3 4print(set_a.isdisjoint(set_b))
Output:
1True
If they share an element:
1set_a = {1, 2, 3} 2set_b = {3, 4, 5} 3 4print(set_a.isdisjoint(set_b))
Output:
1False
Iterating Through a Set
You can use a for loop to iterate over a set:
1languages = {"Python", "Java", "C++"} 2 3for language in languages: 4 print(language)
The order of output may vary.
Do not write code that depends on the iteration order of a set.
If you need predictable ordering, use sorted():
1languages = {"Python", "Java", "C++"} 2 3for language in sorted(languages): 4 print(language)
Possible output:
1C++ 2Java 3Python
Sorting a Set
A set itself is unordered, but you can create a sorted list from it.
1numbers = {40, 10, 30, 20} 2 3sorted_numbers = sorted(numbers) 4 5print(sorted_numbers)
Output:
1[10, 20, 30, 40]
Notice that sorted() returns a list, not a set.
Set Comprehension
Python also supports set comprehensions, which provide a concise way to create sets.
For example:
1numbers = {1, 2, 3, 4, 5} 2 3squares = {number ** 2 for number in numbers} 4 5print(squares)
Output:
1{1, 4, 9, 16, 25}
You can also use conditions:
1numbers = range(1, 11) 2 3even_numbers = {number for number in numbers if number % 2 == 0} 4 5print(even_numbers)
Output:
1{2, 4, 6, 8, 10}
Set comprehensions are useful when you want to create a set from existing iterable data while automatically eliminating duplicates.
Sets and Hashable Elements
Set elements must be hashable.
Common hashable values include:
- Integers
- Floats
- Strings
- Booleans
- Tuples containing only hashable elements
- Frozen sets
For example:
1data = {10, "Python", 3.14, True} 2 3print(data)
A tuple can also be a set element:
1coordinates = {(10, 20), (30, 40)} 2 3print(coordinates)
But a list cannot be a set element:
1data = {[10, 20]}
This raises:
1TypeError: unhashable type: 'list'
Frozen Sets
A frozenset is an immutable version of a set.
Unlike a normal set, a frozenset cannot be modified after creation.
1numbers = frozenset([1, 2, 3, 4]) 2 3print(numbers)
Output:
1frozenset({1, 2, 3, 4})
You cannot use add():
1numbers.add(5)
Error:
1AttributeError: 'frozenset' object has no attribute 'add'
Frozensets are useful when you need set-like behavior but the collection must remain unchanged.
They can also be used as dictionary keys:
1permissions = frozenset({"read", "write"}) 2 3roles = { 4 permissions: "Editor" 5} 6 7print(roles)
A normal mutable set cannot be used as a dictionary key.
Set vs List vs Tuple
Choosing the right collection is important in Python.
| Feature | List | Tuple | Set |
|---|---|---|---|
| Syntax | [] | () | {} |
| Ordered | Yes | Yes | No |
| Mutable | Yes | No | Yes |
| Duplicates | Yes | Yes | No |
| Indexing | Yes | Yes | No |
| Slicing | Yes | Yes | No |
| Fast membership testing | Good | Good | Usually very fast |
| Mathematical set operations | No | No | Yes |
| Best for | Changeable sequences | Fixed sequences | Unique collections |
A simple rule:
1Need duplicates and ordering? 2→ List 3 4Need fixed, ordered data? 5→ Tuple 6 7Need unique values and set operations? 8→ Set
Practical Project: Remove Duplicate Values
One of the most common uses of a set is removing duplicate values.
1numbers = [10, 20, 20, 30, 40, 40, 50] 2 3unique_numbers = set(numbers) 4 5print("Original:", numbers) 6print("Unique:", unique_numbers)
Possible output:
1Original: [10, 20, 20, 30, 40, 40, 50] 2Unique: {40, 10, 50, 20, 30}
The exact order of the set is not guaranteed.
If you need the result as a list:
1numbers = [10, 20, 20, 30, 40, 40, 50] 2 3unique_numbers = list(set(numbers)) 4 5print(unique_numbers)
The resulting list may not preserve the original order.
Preserve Order While Removing Duplicates
If preserving the original order matters, do not rely on converting directly to a set.
A simple modern approach is:
1numbers = [10, 20, 20, 30, 40, 40, 50] 2 3unique_numbers = list(dict.fromkeys(numbers)) 4 5print(unique_numbers)
Output:
1[10, 20, 30, 40, 50]
This approach uses dictionary insertion ordering to preserve the first occurrence of each value.
You can also explicitly use a set to track previously seen values:
1numbers = [10, 20, 20, 30, 40, 40, 50] 2 3unique_numbers = [] 4seen = set() 5 6for number in numbers: 7 if number not in seen: 8 seen.add(number) 9 unique_numbers.append(number) 10 11print(unique_numbers)
Output:
1[10, 20, 30, 40, 50]
This pattern is useful when you need more control over the deduplication process.
Practical Project: Find Common Skills
Suppose two developers have different skills:
1developer_a = { 2 "Python", 3 "Django", 4 "SQL", 5 "Git" 6} 7 8developer_b = { 9 "Python", 10 "Docker", 11 "SQL", 12 "Linux" 13} 14 15common_skills = developer_a & developer_b 16 17print("Common Skills:", common_skills)
Possible output:
1Common Skills: {'Python', 'SQL'}
You can also find skills unique to each developer:
1only_a = developer_a - developer_b 2only_b = developer_b - developer_a 3 4print("Only Developer A:", only_a) 5print("Only Developer B:", only_b)
This demonstrates how set operations can solve real-world comparison problems with very little code.
Common Python Set Mistakes
Trying to Access a Set Using an Index
This is invalid:
1numbers = {10, 20, 30} 2 3print(numbers[0])
Error:
1TypeError: 'set' object is not subscriptable
Sets do not support indexing.
If you need indexing, use a list:
1numbers = [10, 20, 30] 2 3print(numbers[0])
Assuming Set Order
Avoid code such as:
1colors = {"Red", "Green", "Blue"} 2 3# Do not assume which value appears first.
Sets are not designed for positional access.
If you need a predictable order:
1colors = {"Red", "Green", "Blue"} 2 3ordered_colors = sorted(colors) 4 5print(ordered_colors)
Creating an Empty Set with {}
This creates a dictionary:
1data = {} 2 3print(type(data))
Use:
1data = set() 2 3print(type(data))
Adding a List to a Set
This is invalid:
1numbers = {1, 2, 3} 2 3numbers.add([4, 5])
Error:
1TypeError: unhashable type: 'list'
If you want to add multiple values, use update():
1numbers = {1, 2, 3} 2 3numbers.update([4, 5]) 4 5print(numbers)
Output:
1{1, 2, 3, 4, 5}
Practice Exercises
Exercise 1: Remove Duplicates
Convert this list into a set:
1numbers = [10, 20, 20, 30, 30, 40, 50, 50] 2 3unique_numbers = set(numbers) 4 5print(unique_numbers)
Exercise 2: Find Common Subjects
Find subjects shared by both students:
1student1 = {"Math", "Science", "English"} 2student2 = {"Science", "Computer", "English"} 3 4common = student1 & student2 5 6print("Common Subjects:", common)
Expected result:
1Common Subjects: {'Science', 'English'}
Exercise 3: Merge Two Sets
Combine two sets using the union operator:
1set1 = {1, 2, 3} 2set2 = {4, 5, 6} 3 4result = set1 | set2 5 6print(result)
Exercise 4: Find Missing Skills
Find which required skills a candidate does not have:
1required = {"Python", "Git", "SQL", "Docker"} 2candidate = {"Python", "Git"} 3 4missing = required - candidate 5 6print("Missing Skills:", missing)
Exercise 5: Check Membership
Check whether a programming language is available:
1languages = {"Python", "Java", "C++"} 2 3language = input("Enter a language: ") 4 5if language in languages: 6 print("Language Available") 7else: 8 print("Language Not Available")
Exercise 6: Check Whether One Set Is a Subset
1required = {"Python", "SQL"} 2skills = {"Python", "SQL", "Docker"} 3 4if required.issubset(skills): 5 print("All required skills are available") 6else: 7 print("Some skills are missing")
Key Takeaways
A Python set is a mutable collection designed to store unique elements.
Remember these important points:
- Create sets with
{}containing values or withset(). - Use
set()to create an empty set. - Sets automatically remove duplicate values.
- Sets are unordered and do not support indexing.
- Use
add()to add one element. - Use
update()to add multiple elements. - Use
remove()to remove a required element. - Use
discard()to remove an element without raising an error if it is missing. - Use
clear()to remove all elements. - Use
pop()to remove an arbitrary element. - Use
union()or|to combine sets. - Use
intersection()or&to find common elements. - Use
difference()or-to find elements unique to one set. - Use
symmetric_difference()or^to find elements that occur in only one of the sets. - Use
issubset()andissuperset()to compare set relationships. - Use
isdisjoint()to check whether two sets have no common elements. - Set elements must be hashable.
- Use
frozensetwhen you need an immutable set.
Understanding sets is essential for writing efficient Python programs, especially when working with unique data, membership checks, filtering, comparison, and mathematical set operations.