In the previous section, you learned the differences between Python lists and tuples and when each data structure should be used. Python also provides another powerful collection data type called a set. Unlike lists and tuples, sets are designed to store only unique values and automatically remove duplicate elements.
Sets are widely used in data analysis, database applications, web development, machine learning, and cybersecurity because they provide fast searching and efficient mathematical operations such as union, intersection, and difference.
In this lesson, you will learn what Python sets are, why they are useful, how to create them, understand their characteristics, and explore practical examples that demonstrate their real-world applications.
After completing this lesson, you will be able to:
A set is an unordered collection of unique elements. Unlike lists and tuples, sets do not maintain the insertion order of elements and do not allow duplicate values.
Sets are mutable, which means elements can be added or removed after creation. However, individual elements inside a set must be immutable, such as numbers, strings, or tuples.
Sets are useful when you need to store unique values or perform mathematical operations on collections of data.
Common uses of sets include:
Sets are created using curly braces {} or the set() function.
fruits = {
"Apple",
"Banana",
"Orange"
}
print(fruits)
Output
{'Apple', 'Banana', 'Orange'}
Python creates a set containing three unique values.
set() Functionnumbers = set([
10,
20,
30,
40
])
print(numbers)
Output
{10, 20, 30, 40}
The set() function converts another iterable into a set.
If duplicate values are provided, Python keeps only one copy.
marks = {
85,
90,
85,
95,
90
}
print(marks)
Output
{85, 90, 95}
The duplicate values are automatically removed.
To create an empty set, use the set() function.
students = set()
print(type(students))
Output
<class 'set'>
Many beginners mistakenly believe that empty curly braces create an empty set.
data = {}
print(type(data))
Output
<class 'dict'>
Empty curly braces create a dictionary, not a set.
To create an empty set, always use:
data = set()
students = {
"Rahul",
"Priya",
"Rahul",
"Amit",
"Priya"
}
print(students)
Output
{'Rahul', 'Priya', 'Amit'}
Duplicate student names are removed automatically.
languages = set([
"Python",
"SQL",
"Python",
"Power BI",
"SQL"
])
print(languages)
Output
{'Python', 'SQL', 'Power BI'}
The set stores only unique programming languages.
Consider the following program.
numbers = {
10,
20,
20,
30
}
print(numbers)
Execution Steps
Output
{10, 20, 30}
{} to create an empty set.In this section, you learned what Python sets are, why they are useful, their characteristics, and how to create them using curly braces and the set() function. You also learned the difference between an empty set and an empty dictionary, explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to access, add, remove, and update set elements, iterate through sets, check membership, and apply these operations in real-world Python programs.
In the previous section, you learned what Python sets are, their characteristics, and how to create them. Since sets are mutable, you can add new elements, remove existing elements, update multiple values at once, and check whether a value exists in a set. Although sets do not support indexing, Python provides several simple methods for managing set data efficiently.
In this section, you will learn how to access set elements, add and remove values, update sets, iterate through sets, check membership, and apply these operations in practical Python programs.
Unlike lists and tuples, sets are unordered collections. This means you cannot access elements using indexes. Instead, you work with sets by iterating through them or checking whether specific values exist.
The most common way to access set elements is by using a for loop.
fruits = {
"Apple",
"Banana",
"Orange"
}
for fruit in fruits:
print(fruit)
Sample Output
Apple
Orange
Banana
The order may vary because sets are unordered.
The in operator checks whether a value exists in a set.
languages = {
"Python",
"SQL",
"Power BI"
}
print("Python" in languages)
print("Java" in languages)
Output
True
False
Membership testing is one of the fastest operations performed by sets.
Python provides several methods to modify sets by adding, removing, or updating elements.
The add() method inserts one new element into a set.
courses = {
"Python",
"SQL"
}
courses.add("Power BI")
print(courses)
Output
{'Python', 'SQL', 'Power BI'}
If the value already exists, nothing changes.
The update() method adds multiple elements from another iterable.
courses = {
"Python",
"SQL"
}
courses.update([
"Power BI",
"Tableau"
])
print(courses)
Output
{'Python', 'SQL', 'Power BI', 'Tableau'}
remove()The remove() method deletes a specified element.
cities = {
"Delhi",
"Mumbai",
"Chennai"
}
cities.remove("Mumbai")
print(cities)
Output
{'Delhi', 'Chennai'}
If the value does not exist, Python raises a KeyError.
discard()The discard() method removes an element without raising an error if the value is missing.
cities = {
"Delhi",
"Mumbai",
"Chennai"
}
cities.discard("Kolkata")
print(cities)
Output
{'Delhi', 'Mumbai', 'Chennai'}
This method is safer when you are unsure whether the value exists.
The pop() method removes and returns an arbitrary element.
colors = {
"Red",
"Green",
"Blue"
}
removed = colors.pop()
print(removed)
print(colors)
Sample Output
Green
{'Red', 'Blue'}
The removed element may vary because sets are unordered.
The clear() method removes all elements from a set.
numbers = {
10,
20,
30
}
numbers.clear()
print(numbers)
Output
set()
students = {
"Rahul",
"Priya"
}
students.add("Amit")
print(students)
Output
{'Rahul', 'Priya', 'Amit'}
courses = {
"Python",
"SQL"
}
courses.update([
"Power BI",
"Excel"
])
print(courses)
Output
{'Python', 'SQL', 'Power BI', 'Excel'}
products = {
"Laptop",
"Mouse",
"Keyboard"
}
if "Mouse" in products:
print("Product Available")
else:
print("Product Not Available")
Output
Product Available
Consider the following program.
languages = {
"Python",
"SQL"
}
languages.add("Power BI")
print(languages)
Execution Steps
add() method receives the value "Power BI".Output
{'Python', 'SQL', 'Power BI'}
remove() without checking whether the value exists.pop() removes the last inserted element.In this section, you learned how to work with Python sets by looping through elements, checking membership, adding values using add() and update(), removing elements with remove(), discard(), and pop(), and clearing an entire set. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn powerful mathematical set operations such as union(), intersection(), difference(), and symmetric_difference(), along with their practical applications.
In the previous section, you learned how to create sets, add and remove elements, update sets, and check membership. One of the biggest advantages of Python sets is their ability to perform mathematical set operations. These operations allow you to compare collections of data, find common elements, remove duplicates, and identify differences efficiently.
Set operations are widely used in data analysis, database management, recommendation systems, machine learning, and cybersecurity because they make comparing large datasets fast and simple.
Python provides several built-in methods for performing mathematical operations on sets. The four most commonly used operations are:
The union() method combines all unique elements from two or more sets.
set1.union(set2)
python_students = {
"Rahul",
"Priya",
"Amit"
}
sql_students = {
"Priya",
"Neha",
"Rohit"
}
all_students = python_students.union(sql_students)
print(all_students)
Sample Output
{'Rahul', 'Priya', 'Amit', 'Neha', 'Rohit'}
Duplicate values appear only once in the resulting set.
The intersection() method returns only the elements that exist in both sets.
python_students = {
"Rahul",
"Priya",
"Amit"
}
sql_students = {
"Priya",
"Amit",
"Rohit"
}
common_students = python_students.intersection(sql_students)
print(common_students)
Output
{'Priya', 'Amit'}
This operation is useful for finding common records.
The difference() method returns the elements that exist in the first set but not in the second set.
python_students = {
"Rahul",
"Priya",
"Amit"
}
sql_students = {
"Priya",
"Rohit"
}
remaining = python_students.difference(sql_students)
print(remaining)
Output
{'Rahul', 'Amit'}
The matching values are removed from the result.
The symmetric_difference() method returns elements that are present in either set but not in both.
set1 = {
10,
20,
30
}
set2 = {
20,
30,
40
}
result = set1.symmetric_difference(set2)
print(result)
Output
{10, 40}
Common elements are excluded from the result.
python_students = {
"Rahul",
"Priya",
"Amit"
}
powerbi_students = {
"Neha",
"Priya",
"Vikas"
}
print(python_students.union(powerbi_students))
Sample Output
{'Rahul', 'Priya', 'Amit', 'Neha', 'Vikas'}
python_students = {
"Rahul",
"Priya",
"Amit"
}
sql_students = {
"Priya",
"Amit",
"Rohit"
}
print(python_students.intersection(sql_students))
Output
{'Priya', 'Amit'}
today_customers = {
"Rahul",
"Priya",
"Amit"
}
yesterday_customers = {
"Priya",
"Neha"
}
print(today_customers.difference(yesterday_customers))
Output
{'Rahul', 'Amit'}
survey_a = {
"Python",
"SQL",
"Excel"
}
survey_b = {
"SQL",
"Power BI",
"Excel"
}
print(survey_a.symmetric_difference(survey_b))
Output
{'Python', 'Power BI'}
union() to combine unique records.intersection() to identify common values.difference() to find missing or exclusive records.symmetric_difference() to compare two datasets.Consider the following program.
set1 = {
10,
20,
30
}
set2 = {
20,
40
}
result = set1.intersection(set2)
print(result)
Execution Steps
intersection() method compares both sets.Output
{20}
union() with intersection().difference() to compare both sets automatically.In this section, you learned the four most important set operations: union(), intersection(), difference(), and symmetric_difference(). You explored practical applications, best practices, performance tips, execution flow, and common beginner mistakes. In the final section, you will review the complete lesson with a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Set Methods: Complete Guide for Beginners.
In this lesson, you learned the fundamentals of Python sets and discovered how they differ from other collection data types such as lists and tuples. A set is an unordered, mutable collection that stores only unique values, making it ideal for removing duplicates and performing mathematical set operations.
You began by understanding what sets are, their characteristics, and how to create them using curly braces and the set() function. You also learned the important difference between an empty set and an empty dictionary.
Next, you explored how to work with set elements by adding, updating, removing, and checking membership. Since sets do not support indexing, you learned how to iterate through them using loops.
Finally, you learned the four most important mathematical set operations: union(), intersection(), difference(), and symmetric_difference(). These operations are widely used in data analysis, database management, cybersecurity, and machine learning to compare collections of unique data efficiently.
Python sets provide excellent performance for membership testing and duplicate removal, making them one of the most useful data structures in Python programming.
set() to create an empty set.add() to insert a single element.update() to add multiple elements.remove() or discard() to delete elements.in operator for fast membership testing.union(), intersection(), difference(), and symmetric_difference() for mathematical set operations.A Python set is an unordered collection of unique elements.
No. Duplicate values are automatically removed.
No. Sets are unordered collections.
No. Sets do not support indexing or slicing.
Use the set() function.
remove() and discard()?remove() raises a KeyError if the element does not exist, whereas discard() does nothing.
union() method do?It combines all unique elements from two or more sets.
intersection() method return?It returns only the elements common to both sets.
Sets use hash-based storage, making membership checks very efficient.
Use sets when working with unique values, removing duplicates, or performing mathematical set operations.
set() function.add().update().remove() and discard().in operator to check whether an element exists.remove() and discard().union() method?intersection() and difference().Create a Python program that manages student enrollments using sets.
Your program should:
union().intersection().difference().symmetric_difference().add().========== STUDENT COURSE ENROLLMENT ==========
Python Students
{'Rahul', 'Priya', 'Amit'}
SQL Students
{'Priya', 'Neha', 'Rohit'}
All Students
{'Rahul', 'Priya', 'Amit', 'Neha', 'Rohit'}
Students in Both Courses
{'Priya'}
Only Python Students
{'Rahul', 'Amit'}
Students in Only One Course
{'Rahul', 'Amit', 'Neha', 'Rohit'}
==============================================
Congratulations! You have successfully learned the fundamentals of Python Sets. You now understand how to create sets, manage unique values, perform membership testing, modify sets, and use powerful mathematical operations to compare collections of data.
In the next lesson, you will learn Python Set Methods: Complete Guide for Beginners. You will explore every important built-in set method, including copy(), clear(), pop(), issubset(), issuperset(), isdisjoint(), update(), and many more with practical examples and real-world applications.