DSA — Sets
What is a Set?
An unordered collection of unique elements.
# Creating sets
s = {1, 2, 3, 4, 5}
s = set([1, 2, 3, 4, 5])
s = set() # Empty set
Set Operations
# Add
s.add(6)
# Remove
s.remove(3)
s.discard(10) # No error if not found
# Membership
3 in s
# Size
len(s)
Set Mathematics
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union
a | b # {1, 2, 3, 4, 5, 6}
# Intersection
a & b # {3, 4}
# Difference
a - b # {1, 2}
# Symmetric Difference
a ^ b # {1, 2, 5, 6}
Use Cases
# Remove duplicates
lst = [1, 2, 2, 3, 3, 3]
unique = list(set(lst))
# Fast membership testing
valid_ids = {101, 102, 103, 104}
if user_id in valid_ids:
print("Valid")
Mini Practice
- Create and manipulate sets
- Perform set operations
- Remove duplicates from a list
- Find common elements
Up Next
Continue with Trees — tree data structure.
Related Topics
Frequently Asked Questions about Sets
What is Sets in DSA?
Sets is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sets?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sets.
Why is Sets important in DSA?
Sets is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.