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 (0)