Python — Collections — 4— Set
What Is a Set?
In Python, a set is an unordered collection of unique elements. Sets are ideal for operations involving membership tests, deduplication, and mathematical set operations like union, intersection, and difference.
Creating a Set
Sets can be created using the set() constructor or curly braces {}.
# Using curly braces
numbers = {1, 2, 3, 4}
# Using set() function
unique_chars = set("hello")
print(numbers) # Output: {1, 2, 3, 4}
print(unique_chars) # Output: {'h', 'e', 'l', 'o'}Key Characteristics of Sets
- Unordered: Elements do not have a specific order.
- Unique Elements: Duplicate values are automatically removed.
- Mutable: Sets themselves are mutable, but their elements must be immutable (e.g., numbers, strings, tuples).
- No Indexing or Slicing: Since sets are unordered, you can’t access elements by position.
Common Operations on Sets
Adding and Removing Elements
# Adding elements
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
# Removing elements
my_set.remove(3)
print(my_set) # Output: {1, 2, 4}
# Discard (does not raise an error if the element is absent)
my_set.discard(10) # No errorSet Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union: Combine elements from both sets
print(A | B) # Output: {1, 2, 3, 4, 5, 6}
# Intersection: Common elements in both sets
print(A & B) # Output: {3, 4}
# Difference: Elements in A but not in B
print(A - B) # Output: {1, 2}
# Symmetric Difference: Elements in A or B but not both
print(A ^ B) # Output: {1, 2, 5, 6}Membership Testing
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # Output: True
print("mango" in fruits) # Output: FalseGet Faheem unnisa’s stories in your inbox
Join Medium for free to get updates from this writer.
Another few methods of Sets
List Vs sets
Example :
Cleaning Financial Data
Suppose you have a list of transaction IDs, some of which are duplicated. You want only unique transaction IDs.
# Raw transaction IDs with duplicates
transaction_ids = [101, 102, 103, 101, 104, 102, 105]
# Use a set to remove duplicates
unique_transactions = set(transaction_ids)
print(unique_transactions) # Output: {101, 102, 103, 104, 105}When to Use Sets
- To ensure uniqueness in datasets (e.g., filtering out duplicate user IDs).
- For mathematical operations (e.g., finding overlapping customer segments).
- For fast lookups (e.g., checking if a user is on a VIP list).
Key Takeaways
- Sets are unordered collections of unique elements.
- They are powerful for operations like deduplication, membership testing, and mathematical set operations.
- Their built-in methods simplify many data management tasks in Python projects.
Explore the power of sets and enhance your Python projects today!







