← Back to Interactive Learning

Python Basics · Lesson 10

Sets

Learn how Python sets store unique values and how to add, remove, compare and analyze collections of data.

What you will learn

  • • What sets are
  • • Creating sets
  • • Unique values
  • • Removing duplicates
  • • add()
  • • remove()
  • • discard()
  • • pop()
  • • Membership with in
  • • Union
  • • Intersection
  • • Difference

Part 1

What is a set?

A set is a collection of unique values. If duplicate values are provided, a set keeps only one occurrence of each value.

numbers = {10, 20, 30}

print(numbers)

CHECK YOUR UNDERSTANDING

What is the main characteristic of a Python set?

CHECK YOUR UNDERSTANDING

What happens to duplicates when values are placed in a set?

Creating a set

Sets are commonly created using curly braces with comma-separated values.

courses = {"Python", "SQL", "Excel"}

print(courses)

CHECK YOUR UNDERSTANDING

Which brackets are commonly used to create a set?

Fill in the Blank

Complete: courses = _____

Creating an empty set

There is an important Python detail here: {} is an empty dictionary, not an empty set. Use set() to create an empty set.

numbers = set()

print(numbers)

CHECK YOUR UNDERSTANDING

Which creates an empty set?

Removing duplicates

One useful feature of sets is removing duplicate values from a collection.

numbers = {10, 20, 10, 30, 20, 40}

print(numbers)

CHECK YOUR UNDERSTANDING

How many unique values are in this set?

CHECK YOUR UNDERSTANDING

Which values remain after duplicates are removed?

add()

The add() method adds an element to a set.

courses = {"Python", "SQL"}

courses.add("Excel")

print(courses)

CHECK YOUR UNDERSTANDING

What does courses.add('Excel') do?

Fill in the Blank

Complete: courses._____("Excel")

remove()

The remove() method removes a specified element from a set. If the element does not exist, Python raises an error.

courses = {"Python", "SQL", "Excel"}

courses.remove("SQL")

print(courses)

CHECK YOUR UNDERSTANDING

Which value is removed?

Fill in the Blank

Complete: courses._____("SQL")

discard()

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

courses = {"Python", "SQL"}

courses.discard("Java")

print(courses)

CHECK YOUR UNDERSTANDING

What happens when Java is not present and discard('Java') is called?

CHECK YOUR UNDERSTANDING

Which method is safer when you are unsure whether an element exists?

pop()

The pop() method removes and returns an arbitrary element from a set. Because sets are unordered, you should not rely on which particular element is removed.

courses = {"Python", "SQL", "Excel"}

removed = courses.pop()

print(removed)
print(courses)

CHECK YOUR UNDERSTANDING

What does set.pop() do?

Membership with in

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

courses = {"Python", "SQL", "Excel"}

print("Python" in courses)

CHECK YOUR UNDERSTANDING

What does "Python" in courses return?

CHECK YOUR UNDERSTANDING

What does "Java" in courses return?

Set Operations

Union

Union combines the unique elements from two sets.

a = {"Python", "SQL"}
b = {"SQL", "Excel"}

result = a | b

print(result)

CHECK YOUR UNDERSTANDING

Which unique values are in the union of a and b?

Fill in the Blank

Complete the union operation: result = a _____ b

Intersection

Intersection returns the elements that are common to both sets.

a = {"Python", "SQL"}
b = {"SQL", "Excel"}

result = a & b

print(result)

CHECK YOUR UNDERSTANDING

What is the intersection of a and b?

Fill in the Blank

Complete the intersection operation: result = a _____ b

Difference

Difference returns elements that are in the first set but not in the second set.

a = {"Python", "SQL"}
b = {"SQL", "Excel"}

result = a - b

print(result)

CHECK YOUR UNDERSTANDING

What is a - b?

Fill in the Blank

Complete the difference operation: result = a _____ b

Predict the output

Think before running the code

numbers = {10, 20, 20, 30}

print(len(numbers))

CHECK YOUR UNDERSTANDING

What will the program print?

Compare

Set vs List vs Tuple

FeatureListTupleSet
Syntax[ ]( ){ }
DuplicatesAllowedAllowedNot stored
MutableYesNoYes
IndexingYesYesNo

CHECK YOUR UNDERSTANDING

Which structure is designed to store unique elements?

CHECK YOUR UNDERSTANDING

Which structure supports indexing such as data[0]?

Data Analytics Connection

Sets for finding unique data

Sets are useful when you need to identify unique categories, products, customers or other values in a dataset.

regions = [
    "North",
    "South",
    "North",
    "East",
    "South"
]

unique_regions = set(regions)

print(unique_regions)

CHECK YOUR UNDERSTANDING

Why convert regions to a set?

CHECK YOUR UNDERSTANDING

How many unique regions are present?

Debug the set code

courses = {"Python", "SQL"}

courses.append("Excel")

print(courses)

CHECK YOUR UNDERSTANDING

Why does this code fail?

Fill in the Blank

Fix the code: courses._____("Excel")

Practice

Complete the set operations

Fill in the Blank

Add an element: courses._____("Python")

Fill in the Blank

Remove an element: courses._____("SQL")

Fill in the Blank

Safely remove an element: courses._____("Java")

Fill in the Blank

Find unique values: unique = _____(data)

Fill in the Blank

Check membership: Python _____ courses

Fill in the Blank

Find common values: result = a _____ b

Mini Challenge

Find unique courses

Imagine a student database contains repeated course names. Convert the list into a set to identify the unique courses.

courses = [
    "Python",
    "SQL",
    "Python",
    "Excel",
    "SQL",
    "Power BI"
]

unique_courses = set(courses)

print(unique_courses)

Question: How many unique courses are there?

Answer: 4

Final Challenge

Compare two student groups

Two groups of students are learning different technologies. Use sets to identify students who are in both groups, students unique to the first group and all unique students.

group_a = {"Aman", "Riya", "Rahul"}
group_b = {"Riya", "Neha", "Rahul"}

common = group_a & group_b
only_a = group_a - group_b
all_students = group_a | group_b

print(common)
print(only_a)
print(all_students)

Common students: Riya, Rahul

Only in Group A: Aman

Total unique students: 4

Lesson recap

  • ✓ Sets store unique values.
  • ✓ Duplicate values are not stored.
  • ✓ set() creates an empty set.
  • ✓ add() adds an element.
  • ✓ remove() removes an element and can raise an error if missing.
  • ✓ discard() removes an element without raising an error if missing.
  • ✓ pop() removes and returns an arbitrary element.
  • ✓ in checks membership.
  • ✓ | performs union.
  • ✓ & performs intersection.
  • ✓ - performs difference.
  • ✓ Sets are useful for finding unique data.