Python for Data Analytics • Lesson 10

Sets

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

Your progress0%

0 of 8 concepts completed

Complete the activity and related MCQ to unlock the next concept.

Concept 1SET

What Is a Set?

A set is a collection of unique values. Order is not preserved, and duplicate values are silently discarded. Sets are written with curly braces { } when they contain values.

Learn by Seeing

Unique values, unordered

numbers = {10, 20, 30}

print(numbers)
# {10, 20, 30} (order may vary)

A set always contains each value at most once.

Edit the values — see duplicates collapse into unique entries:

list input

10202030

as a set

102030

Interactive Activity

How many values are stored in numbers = {10, 20, 20, 30}?

Hint: Duplicates are dropped, so only unique values remain.

Python Analyst Mindset

Unique values and set algebra

"How many distinct customers?" "Which products appear in both months?" "Which regions are missing from this dataset?" — these are all set questions. Sets give you deduplication and comparison in a single line.

01

Deduplicate

set(data) removes repeats.

02

Test membership

in is fast and Boolean.

03

Compare

| & - for group comparisons.

04

Analyze

Count unique categories in one line.

Frequently Asked Questions

Sets — FAQs

Why does create a dictionary, not a set?

Python reserves for empty dictionaries. Use set() when you need an empty set.

What is the difference between remove() and discard()?

remove() raises a KeyError when the element is missing. discard() does nothing.

Can I sort a set?

Sets are unordered, so no. Convert to a list first (sorted(my_set)) if you need order.

What does | do again?

| is union — every distinct element from both sets, with duplicates removed.

Lesson Summary

What you learned

Unique values

A set keeps one copy of each element.

set() for empty

creates a dictionary; set() creates an empty set.

add / remove / discard

add inserts; discard removes safely.

pop() and in

pop removes an arbitrary element; in tests membership.

Union |

Everything from both sets.

Intersection & and Difference -

Shared values, and values unique to the left set.