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)
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)
Output:
{1, 2, 3, 4, 5}
Duplicates are automatically removed.
🔹 Adding Items to a Set
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
🔹 Removing Items
numbers = {1, 2, 3, 4}
numbers.remove(2)
print(numbers)
💡 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:
- Creates a list with repeated numbers
- Converts it into a set
- 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)