DEV Community

still-purrfect
still-purrfect

Posted on

Sets in Python: Working With Unique Values

Have you ever had duplicate data and wished you could just remove repeats automatically?
That’s exactly what sets do.
So far, we’ve worked with lists, tuples, dictionaries, and other data types.
Now we’re looking at something simpler but very powerful: sets.
A set is a collection of items that does not allow duplicates.

🔹 Creating a Set

numbers = {1, 2, 3, 4, 5}
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Sets use curly brackets, just like dictionaries but they only store values.

🔹 Removing Duplicates Automatically

numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Output:
{1, 2, 3, 4, 5}
Duplicates are automatically removed.

🔹 Adding Items to a Set

numbers = {1, 2, 3}

numbers.add(4)

print(numbers)
Enter fullscreen mode Exit fullscreen mode

🔹 Removing Items

numbers = {1, 2, 3, 4}

numbers.remove(2)

print(numbers)
Enter fullscreen mode Exit fullscreen mode

💡 Why Sets Matter

Sets are useful when you need:

  • Unique values only
  • Fast membership checks
  • Cleaned-up data They are often used in:
  • Data cleaning
  • Removing duplicates from lists
  • Comparing groups of items

Think of sets as a “no repetition allowed” container.

🌱 Challenge

Write a program that:

  1. Creates a list with repeated numbers
  2. Converts it into a set
  3. Prints the cleaned unique values

Bonus: Try adding a new number to the set and printing it again.

Next, we’ll explore inheritance, where you learn how classes can build on each other like real systems in software development.

Top comments (1)

Collapse
 
ggle_in profile image
HARD IN SOFT OUT

Sets are one of those "why didn't I learn this sooner" features

I remember writing ugly loops to remove duplicates from lists before I discovered sets. list(set(my_list)) is still one of my favorite one-liners.

Your point about fast membership checks is worth emphasizing. Checking if x in set is O(1) on average, while if x in list is O(n). For large datasets, that difference is massive.

A tiny real‑world example I use often:

# Get unique visitors from a log file
visitors = {'alice', 'bob', 'alice', 'charlie', 'bob'}
unique_visitors = visitors  # {'alice', 'bob', 'charlie'}
Enter fullscreen mode Exit fullscreen mode

Also, don't forget set operations – union (|), intersection (&), and difference (-) are super handy for comparing groups.

Great intro as always. Looking forward to the inheritance article next.

Cheers,
Jack
DEV.to/ggle.in