Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Sets

Learn how Python Sets store unique values and perform powerful operations such as Union, Intersection and Difference.

What is a Set?

A Set is a built-in Python data structure used to store a collection of unique values.

Sets are especially useful when duplicate values need to be removed or when we need to compare collections of data.

  • Stores unique values
  • Mutable
  • Does not support indexing
  • Does not guarantee a fixed display order
  • Supports mathematical set operations

Creating a Set

Sets are commonly created using curly braces {}.

courses = {"Python", "Java", ".NET"}

print(courses)

The order in which elements are displayed should not be relied upon.

Duplicate Values

A Set automatically removes duplicate values.

courses = {
    "Python",
    "Java",
    "Python",
    ".NET",
    "Java"
}

print(courses)

The resulting Set contains only unique values.

{'Python', 'Java', '.NET'}

Creating an Empty Set

An empty pair of curly braces creates an empty Dictionary, not an empty Set.

data = {}

print(type(data))

Output:

<class 'dict'>

Correct Way

data = set()

print(type(data))

Output:

<class 'set'>

Adding Elements using add()

The add() method adds one element to a Set.

courses = {"Python", "Java"}

courses.add(".NET")

print(courses)
Output
{'Python', 'Java', '.NET'}

The new value is added to the Set if it is not already present.

Adding Multiple Elements using update()

The update() method can add multiple values from another iterable.

courses = {"Python", "Java"}

more_courses = {".NET", "MERN"}

courses.update(more_courses)

print(courses)
Output
{'Python', 'Java', '.NET', 'MERN'}

All unique values from the second collection are added to the Set.

Removing Elements

remove()

The remove() method removes a specified element.

courses = {"Python", "Java", ".NET"}

courses.remove("Java")

print(courses)
Output
{'Python', '.NET'}

If the specified element does not exist, remove() raises a KeyError.

discard()

The discard() method also removes an element, but does not raise an error if the element is missing.

courses = {"Python", "Java", ".NET"}

courses.discard("PHP")

print(courses)
Output
{'Python', 'Java', '.NET'}

pop()

The pop() method removes and returns an arbitrary Set element.

courses = {"Python", "Java", ".NET"}

removed_course = courses.pop()

print("Removed:", removed_course)
print("Remaining:", courses)
Output
Removed: Python
Remaining: {'Java', '.NET'}

clear()

The clear() method removes all elements from the Set.

courses = {"Python", "Java", ".NET"}

courses.clear()

print(courses)

Output:

set()

Finding Set Length

The len() function returns the number of unique elements.

courses = {"Python", "Java", ".NET"}

print(len(courses))

Output:

3

Checking Membership

The in operator checks whether an element exists in a Set.

courses = {"Python", "Java", ".NET"}

print("Python" in courses)
print("PHP" in courses)

Output:

True
False

Looping Through a Set

A for loop can be used to process each element of a Set.

courses = {"Python", "Java", ".NET"}

for course in courses:
    print(course)

Since Sets are unordered collections, the display order should not be assumed.

Set Union

Union combines the unique elements from two Sets.

python_students = {
    "Rahul",
    "Sneha",
    "Amit"
}

java_students = {
    "Amit",
    "Priya",
    "Sneha"
}

all_students = python_students | java_students

print(all_students)

The | operator performs Union.

union() Method

result = python_students.union(java_students)

print(result)
Output
{'Rahul', 'Sneha', 'Amit', 'Priya'}

Set Intersection

Intersection returns values that are common to both Sets.

python_students = {
    "Rahul",
    "Sneha",
    "Amit"
}

java_students = {
    "Amit",
    "Priya",
    "Sneha"
}

common_students = python_students & java_students

print(common_students)

The & operator performs Intersection.

intersection() Method

result = python_students.intersection(java_students)

print(result)

Set Difference

Difference returns elements that exist in the first Set but not in the second Set.

python_students = {
    "Rahul",
    "Sneha",
    "Amit"
}

java_students = {
    "Amit",
    "Priya",
    "Sneha"
}

only_python = python_students - java_students

print(only_python)

The - operator performs Difference.

difference() Method

result = python_students.difference(java_students)

print(result)

Symmetric Difference

Symmetric Difference returns values that exist in either Set, but not in both.

python_students = {
    "Rahul",
    "Sneha",
    "Amit"
}

java_students = {
    "Amit",
    "Priya",
    "Sneha"
}

result = python_students ^ java_students

print(result)

The ^ operator performs Symmetric Difference.

symmetric_difference()

result = python_students.symmetric_difference(
    java_students
)

print(result)

Checking Subset

A Set is a subset if every element of the first Set is present in the second Set.

python_students = {
    "Rahul",
    "Sneha"
}

all_students = {
    "Rahul",
    "Sneha",
    "Amit",
    "Priya"
}

print(python_students.issubset(all_students))

Output:

True

Checking Superset

A Set is a superset if it contains every element of another Set.

all_students = {
    "Rahul",
    "Sneha",
    "Amit",
    "Priya"
}

python_students = {
    "Rahul",
    "Sneha"
}

print(all_students.issuperset(python_students))

Output:

True

Checking Disjoint Sets

Two Sets are disjoint when they have no common elements.

python_students = {
    "Rahul",
    "Sneha"
}

java_students = {
    "Amit",
    "Priya"
}

print(python_students.isdisjoint(java_students))

Output:

True

Important Set Operations

Operation Operator Method Purpose
Union | union() Combines unique values
Intersection & intersection() Returns common values
Difference - difference() Returns values only in first Set
Symmetric Difference ^ symmetric_difference() Returns non-common values
Subset — issubset() Checks subset relationship
Superset — issuperset() Checks superset relationship
Disjoint — isdisjoint() Checks for no common values

Removing Duplicates from a List

One of the most practical uses of a Set is removing duplicate values from a List.

courses = [
    "Python",
    "Java",
    "Python",
    ".NET",
    "Java"
]

unique_courses = set(courses)

print(unique_courses)

The Set contains only unique course names.

Converting Set to List

A Set can be converted into a List using list().

courses = {"Python", "Java", ".NET"}

course_list = list(courses)

print(course_list)

Remember that the order of the resulting List should not be assumed unless you explicitly sort it.

CIIT Example 🤓📩

Suppose CIIT has students enrolled in Python and .NET courses and wants to find students who are common to both courses.

python_students = {
    "Rahul",
    "Sneha",
    "Amit",
    "Neha"
}

dotnet_students = {
    "Amit",
    "Neha",
    "Priya"
}

common_students = python_students & dotnet_students

print("Students in both courses:")
print(common_students)

Intersection helps identify students enrolled in both course groups.

Set vs List vs Tuple

Feature List Tuple Set
Syntax [] () {}
Ordered Yes Yes No guaranteed order
Mutable Yes No Yes
Duplicates Allowed Allowed Not allowed
Indexing Supported Supported Not supported
Main Use Changing collections Fixed collections Unique values and set operations

Common Mistakes

  1. Trying to access Set elements using an index such as courses[0].
  2. Assuming that Set elements will always appear in a particular order.
  3. Using {} when an empty Set is required.
  4. Forgetting that duplicate values are automatically removed.
  5. Using remove() when the requested element may not exist and then unexpectedly getting a KeyError.

Interview Points

  • What is a Set in Python?
  • Why does a Set remove duplicate values?
  • What is the difference between remove() and discard()?
  • What is Set Union?
  • What is Set Intersection?
  • What is the difference between Difference and Symmetric Difference?
  • Can we access Set elements using indexes?
  • How can you remove duplicate values from a List using a Set?

CIIT Learning Point

Sets are extremely useful when uniqueness, membership checking and comparison between collections are important. Union, Intersection, Difference and Symmetric Difference are commonly used when processing real-world data.

CIIT Practice Tasks

  1. Create a Set containing five programming languages.
  2. Add two new languages using add().
  3. Remove one language using remove().
  4. Create two Sets containing Python and .NET students and find common students.
  5. Find students who are enrolled only in Python.
  6. Find all unique students from both courses.
  7. Take a List containing duplicate values and remove duplicates using a Set.

Summary :

Python Sets are mutable collections that store unique values and do not support indexing. They are useful for removing duplicates, membership checking and comparing collections. Important operations include Union, Intersection, Difference and Symmetric Difference. Methods such as add(), update(), remove(), discard(), pop(), clear(), issubset(), issuperset() and isdisjoint() are commonly used while working with Sets.