9.1 Introduction to Sets
A set is a Python collection used to store unique values. Unlike a list or tuple, a set does not keep duplicate items and does not use numbered positions for normal access. Sets are helpful when you care about whether a value exists, when you need to remove duplicates, or when you want to compare groups of values.
Example
colors = {"red", "green", "blue"}
print(colors)
Output
{'red', 'green', 'blue'}
Output explanation: Python displays the three unique values as a set. The order may appear differently because sets are unordered.
9.2 Creating Sets
You create a set by placing comma-separated values inside curly braces. A set can contain strings, numbers, Boolean values, or other immutable objects. You may also create a set from another collection by using the set() function. Python automatically removes repeated values while building the set.
Example
numbers = {10, 20, 30, 20}
print(numbers)
Output
{10, 20, 30}
Output explanation: The value 20 was written twice, but the set keeps only one copy of each value.
9.3 Creating Empty Sets
An empty set must be created with set(), not with empty curly braces. Empty curly braces create an empty dictionary instead. This is an important beginner detail. After creating the empty set, you can add values to it later with methods such as add() or update().
Example
items = set()
print(items)
print(type(items))
Output
set()
<class 'set'>
Output explanation: The first line shows an empty set. The second line confirms that the object is a set.
9.4 Unique Values
Every value in a set must be unique. When duplicate values are included, Python keeps only one copy. This feature makes sets very useful for cleaning repeated information. For example, a set can create a unique list of visitor names, product categories, email addresses, or numbers without writing a manual duplicate-checking loop.
Example
names = {"Ali", "Sara", "Ali", "Mina"}
print(names)
print(len(names))
Output
{'Ali', 'Sara', 'Mina'}
3
Output explanation: Ali appears only once, so the set contains three unique names.
9.5 Unordered Collections
Sets are described as unordered because their items are not stored for position-based access like list items. You should not expect a set to print values in the same order that you typed them. Because sets have no reliable indexes, expressions such as my_set[0] are invalid. Use membership checks or loops instead.
Example
letters = {"a", "b", "c"}
print(letters)
Output
{'c', 'a', 'b'}
Output explanation: The values are correct, but their displayed order may differ between runs or Python environments.
9.6 Adding Items
The add() method places one new item into a set. If the value already exists, the set remains unchanged because duplicates are not allowed. This method is useful when your program discovers or receives one value at a time, such as adding a new category, visitor, tag, or selected option.
Example
fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)
Output
{'apple', 'banana', 'orange'}
Output explanation: The add() method inserts orange into the existing set.
9.7 Updating Sets
The update() method adds several values to a set at one time. You can provide another set, a list, a tuple, or another iterable collection. Python reads each value and adds it if it is not already present. Existing duplicates are ignored, so the final collection still contains only unique values.
Example
skills = {"HTML", "CSS"}
skills.update(["Python", "HTML", "SQL"])
print(skills)
Output
{'HTML', 'CSS', 'Python', 'SQL'}
Output explanation: Python and SQL are added. HTML is ignored because it already exists.
9.8 Removing Items
Python provides several ways to remove values from a set. The remove() method removes a known value, discard() safely removes a value if present, pop() removes an arbitrary value, and clear() removes everything. Choosing the correct method depends on whether the value must exist and whether you need to keep the set itself.
Example
animals = {"cat", "dog", "bird"}
animals.remove("dog")
print(animals)
Output
{'cat', 'bird'}
Output explanation: The remove() method finds dog and deletes it from the set.
9.9 remove() vs discard()
Both remove() and discard() can delete a specific value. The important difference appears when the value is missing. remove() raises a KeyError, while discard() finishes safely without changing the set. Use remove() when a missing value indicates a real problem, and use discard() when absence is acceptable.
Example
colors = {"red", "blue"}
colors.discard("green")
print(colors)
Output
{'red', 'blue'}
Output explanation: Green is not present, but discard() does not produce an error.
9.10 Using pop()
The pop() method removes and returns one arbitrary item from a set. Because sets are unordered, you should not predict which value will be removed. Store the returned item in a variable when you need to know what was taken out. Calling pop() on an empty set raises a KeyError.
Example
numbers = {10, 20, 30}
removed = numbers.pop()
print(removed)
print(numbers)
Output
10
{20, 30}
Output explanation: One arbitrary item is returned and removed. The exact removed number may differ.
9.11 Clearing Sets
The clear() method removes every item from a set but keeps the set variable available. After clearing, you can add new values and continue using the same object. This is different from deleting the variable. Clearing is useful when resetting selected options, temporary results, visited pages, or other collected information.
Example
tasks = {"email", "study", "shop"}
tasks.clear()
print(tasks)
Output
set()
Output explanation: All tasks are removed, leaving an empty set that can still be used.
9.12 Deleting Sets
The del statement deletes the set variable itself, not only its items. After deletion, trying to use the variable produces a NameError because the name no longer exists. Use del when the entire variable is no longer needed. Use clear() instead when you want to keep an empty reusable set.
Example
codes = {101, 102, 103}
del codes
print("The set variable was deleted.")
Output
The set variable was deleted.
Output explanation: The codes variable is removed. The program prints a separate confirmation message.
9.13 Checking Membership
The in operator checks whether a value exists inside a set. It returns True when the value is found and False when it is missing. The not in operator performs the opposite check. Set membership tests are usually fast, making sets useful for allowed values, blocked names, registered users, and lookup collections.
Example
allowed = {"read", "write", "print"}
print("write" in allowed)
print("delete" in allowed)
Output
True
False
Output explanation: Write exists in the set, while delete does not.
9.14 Looping Through Sets
You can process every set item with a for loop. During each repetition, Python places one item into the loop variable. Because sets are unordered, the printing order is not guaranteed. Looping is useful for displaying unique tags, checking permissions, calculating results, or performing the same operation on every unique value.
Example
languages = {"Python", "Java", "C++"}
for language in languages:
print(language)
Output
Python
Java
C++
Output explanation: The loop prints every language once. The order may be different when the program runs.
9.15 Set Union
A union combines all unique values from two or more sets. You can create it with the union() method or the vertical bar operator. Values that occur in both sets appear only once in the result. Union is useful for combining customer groups, course lists, permissions, product tags, or available features.
Example
group_a = {"Ali", "Sara"}
group_b = {"Sara", "Mina"}
all_students = group_a | group_b
print(all_students)
Output
{'Ali', 'Sara', 'Mina'}
Output explanation: The union includes every unique name from both groups. Sara appears once.
9.16 Set Intersection
An intersection returns only values shared by both sets. You can use intersection() or the ampersand operator. This operation helps find common students, shared products, mutual interests, overlapping permissions, or matching records. If the sets share no values, the intersection result is an empty set.
Example
math = {"Ali", "Sara", "John"}
science = {"Sara", "John", "Mina"}
both = math & science
print(both)
Output
{'Sara', 'John'}
Output explanation: Sara and John are the only names present in both sets.
9.17 Set Difference
A set difference returns values found in the first set but not in the second. You can use difference() or the minus operator. The direction matters because A minus B is usually different from B minus A. Difference is useful for finding missing registrations, unavailable products, or unmatched records.
Example
registered = {"Ali", "Sara", "Mina"}
paid = {"Ali", "Mina"}
not_paid = registered - paid
print(not_paid)
Output
{'Sara'}
Output explanation: Sara is registered but does not appear in the paid set.
9.18 Symmetric Difference
A symmetric difference returns values that belong to either set but not to both. Shared values are removed from the result. You can use symmetric_difference() or the caret operator. This operation is useful when comparing changed selections, different memberships, mismatched records, or values unique to only one group.
Example
set_a = {1, 2, 3}
set_b = {3, 4, 5}
result = set_a ^ set_b
print(result)
Output
{1, 2, 4, 5}
Output explanation: Three is shared and removed. The other values belong to only one set.
9.19 Subsets
A set is a subset of another set when every one of its values also exists in the other set. Use issubset() or the less-than-or-equal operator to test this relationship. Subset checks are useful for confirming that required permissions, selected ingredients, completed lessons, or requested features belong to an allowed larger collection.
Example
required = {"name", "email"}
submitted = {"name", "email", "phone"}
print(required.issubset(submitted))
Output
True
Output explanation: Every required field is present in the submitted set.
9.20 Supersets
A set is a superset when it contains every value from another set. Use issuperset() or the greater-than-or-equal operator. Superset checks are the reverse of subset checks. They help confirm that a user has all required permissions, a recipe has needed ingredients, or a record contains every required category.
Example
permissions = {"read", "write", "print"}
required = {"read", "print"}
print(permissions.issuperset(required))
Output
True
Output explanation: Permissions contains both values from the required set.
9.21 Disjoint Sets
Two sets are disjoint when they have no values in common. The isdisjoint() method returns True when there is no overlap and False when at least one shared item exists. This check is useful for detecting schedule conflicts, incompatible categories, separate user groups, or whether two collections contain any matching values.
Example
morning = {"Ali", "Sara"}
evening = {"John", "Mina"}
print(morning.isdisjoint(evening))
Output
True
Output explanation: The two groups share no names, so they are disjoint.
9.22 Frozen Sets
A frozen set is an immutable version of a normal set. After creation, its items cannot be added, removed, or cleared. You create one with frozenset(). Frozen sets still support membership tests and comparison operations. Because they cannot change, they may be used as dictionary keys or values inside another set.
Example
fixed_colors = frozenset(["red", "green", "blue"])
print(fixed_colors)
print("red" in fixed_colors)
Output
frozenset({'red', 'green', 'blue'})
True
Output explanation: Python creates an unchangeable set and confirms that red is one of its values.
9.23 Set Comprehensions
A set comprehension creates a set with a compact expression and loop. It is similar to a list comprehension, but it uses curly braces and automatically removes duplicate results. Set comprehensions are useful for transforming numbers, changing text, filtering values, or creating unique calculated results in one readable statement.
Example
squares = {number * number for number in range(1, 6)}
print(squares)
Output
{1, 4, 9, 16, 25}
Output explanation: The comprehension squares each number from one through five and stores the unique results.
9.24 Removing Duplicate Values
Converting a list to a set is a simple way to remove duplicate values. Python keeps one copy of each item. However, the original list order may not be preserved. When order matters, additional techniques are needed. This approach is useful for cleaning repeated names, numbers, tags, categories, or imported data.
Example
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = set(numbers)
print(unique_numbers)
Output
{1, 2, 3, 4}
Output explanation: Repeated twos and threes are removed, leaving one copy of each number.
9.25 Mathematical Set Operations
Python sets support the same main ideas used in mathematical set theory: union, intersection, difference, symmetric difference, subset, superset, and disjoint tests. These operations let programs compare groups without complicated loops. They are useful in data analysis, permissions, recommendations, search systems, school records, and many classification tasks.
Example
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)
print(a & b)
print(a - b)
Output
{1, 2, 3, 4, 5}
{3}
{1, 2}
Output explanation: The first result is the union, the second is the intersection, and the third is the difference.
9.26 Sets vs Lists and Tuples
Lists are ordered and changeable, tuples are ordered and normally unchangeable, and sets are unordered collections of unique values. Choose a list when item order and duplicates matter. Choose a tuple for fixed ordered data. Choose a set for membership testing, duplicate removal, and mathematical comparisons between groups.
Example
my_list = [1, 1, 2]
my_tuple = (1, 1, 2)
my_set = {1, 1, 2}
print(my_list)
print(my_tuple)
print(my_set)
Output
[1, 1, 2]
(1, 1, 2)
{1, 2}
Output explanation: The list and tuple keep duplicates, while the set removes the repeated value.
9.27 Practical Set Applications
Sets are useful in real programs for finding unique visitors, shared interests, missing permissions, common products, repeated records, and differences between groups. Their membership tests and comparison operations can replace longer loops. A common application is comparing registered users with attendees to discover who has not arrived.
Example
registered = {"Ali", "Sara", "John", "Mina"}
attended = {"Ali", "Mina"}
absent = registered - attended
print(absent)
Output
{'Sara', 'John'}
Output explanation: Sara and John are registered but are not included in the attendance set.
9.28 Chapter Practice Exercises
Practice helps you remember how sets behave. In these exercises, create sets, add and remove values, test membership, remove duplicates, and compare groups. Try each task before checking a solution. Pay attention to unordered output and remember that duplicate values appear only once inside a set.
Example
values = {2, 4, 6}
values.add(8)
values.discard(2)
print(values)
print(6 in values)
Output
{4, 6, 8}
True
Output explanation: Eight is added, two is removed, and the membership test confirms that six remains.
9.29 Chapter Mini Project
This mini project compares students registered for two clubs. It finds everyone involved, students attending both clubs, and students attending only one club. The project combines union, intersection, and symmetric difference. It demonstrates how a few clear set operations can answer several practical questions without long nested loops.
Example
art_club = {"Ali", "Sara", "Mina"}
music_club = {"Sara", "John", "Mina"}
all_students = art_club | music_club
both_clubs = art_club & music_club
one_club_only = art_club ^ music_club
print("All students:", all_students)
print("Both clubs:", both_clubs)
print("One club only:", one_club_only)
Output
All students: {'Ali', 'Sara', 'Mina', 'John'}
Both clubs: {'Sara', 'Mina'}
One club only: {'Ali', 'John'}
Output explanation: The union finds every student, the intersection finds shared members, and the symmetric difference finds students in only one club.