Python Sets Explained for Beginners (With Simple Examples)
Python Sets Explained for Beginners (With Simple Examples)
Introduction
In the previous post, we learned about Python Tuples. Now let’s explore another important data structure in Python called Set.
Sets are used to store unique values and are very useful in real-world programming.
---What is a Set in Python?
A set is a collection of items that is:
- Unordered
- Mutable (can be changed)
- Does not allow duplicate values
How to Create a Set
Sets are created using curly brackets { }.
numbers = {1, 2, 3, 4}
print(numbers)
Duplicate Values in Sets
Let’s see what happens when we add duplicate values.
data = {1, 2, 2, 3, 4, 4}
print(data)
Set with Different Data Types
A set can store different data types.
info = {"Ayush", 22, True, 75.5}
print(info)
Accessing Set Elements
You cannot access set elements using index numbers because sets are unordered.
You can access elements using a loop.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Adding Elements to a Set
Use the add() method to add elements.
fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)
Removing Elements from a Set
Use remove() or discard().
fruits = {"apple", "banana", "orange"}
fruits.remove("banana")
print(fruits)
discard() if you want to avoid errors.
Set Length
Use len() to find the number of elements.
numbers = {10, 20, 30}
print(len(numbers))
Difference Between List, Tuple, and Set
- List → Ordered, Mutable, Allows duplicates
- Tuple → Ordered, Immutable, Allows duplicates
- Set → Unordered, Mutable, No duplicates
When Should You Use Sets?
- To store unique values
- To remove duplicates from data
- For faster membership testing
What You Learned in This Post
- What is a set
- How to create sets
- Adding and removing elements
- Difference between list, tuple, and set
What’s Next?
Now that you understand sets, it’s time to learn the most powerful data structure in Python.
Next Post: Python Dictionary Explained for Beginners
---👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Comments
Post a Comment