What is a Set?
A set in Python is a collection of unordered, unindexed, and unique items.
It is represented by curly braces {} or the set() function.
Example:
fruits = {"apple", "banana", "cherry"}
Here, we have created a set named fruits. It contains 3 items.
Set Features
- Unordered → The items have no fixed order. Printing may show a different order.
- Unchangeable items → You cannot change elements directly, only add/remove entire items.
- Unique items → Duplicates are not allowed.
Important Methods in Set { }
| Method | Description | Example |
|---|---|---|
add(x) | Add element | s.add(5) |
remove(x) | Remove element (error if missing) | s.remove(3) |
discard(x) | Remove element (no error if missing) | s.discard(10) |
pop() | Remove and return a random element | s.pop() |
clear() | Remove all elements | s.clear() |
copy() | Return shallow copy | t = s.copy() |
union(*others) | Return union of sets | s.union(t) or `s |
update(*others) | Union in place | s.update(t) or `s |
intersection(*others) | Return common elements | s & t |
intersection_update(*others) | Keep only common (in place) | s &= t |
difference(*others) | Return items only in s | s - t |
difference_update(*others) | Remove items in other (in place) | s -= t |
symmetric_difference(other) | Items in either but not both | s ^ t |
symmetric_difference_update(other) | Update with symmetric diff | s ^= t |
issubset(other) | Check if s ⊆ other | s <= t |
issuperset(other) | Check if s ⊇ other | s >= t |
isdisjoint(other) | True if no common elements | s.isdisjoint(t) |
Methods That Don’t Work with Sets
append, insert, extend, sort, reverse, index, count
👉 Since sets are unordered, these list methods cannot be used directly.
If you want such operations, convert the set to a list first.
Example:
people = {"Subin Thapa", "Garima Sapkota", "Bishworaj Poudel", "Gokarna Parajuli"}
result = list(people)
print(result)
Using Sets in Everyday Life
1. Create a Set
fruits = {"apple", "banana", "cherry"}
2. Check for Item in Set
is_in_set = "banana" in fruits
print(is_in_set) # True
3. Add Item
fruits.add("orange")
4. Remove Item
fruits.remove("banana")
5. Mixed Items
mixed_set = {1, "apple", 3.14}
Examples
Example 1: Unique Email Addresses
emails = ["alice@example.com", "bob@example.com", "alice@example.com", "bob@example.com"]
unique_emails = set(emails)
print("Unique Emails:", unique_emails)
Example 2: Finding Common Students (Intersection)
course_A_students = {"Garima", "Bob", "Ram"}
course_B_students = {"Charlie", "Garima", "Alice"}
common_students = course_A_students.intersection(course_B_students)
print("Common Students:", common_students)
Example 3: Union, Difference, Symmetric Difference
project_A_tasks = {"task1", "task2", "task3"}
project_B_tasks = {"task2", "task4", "task5"}
all_tasks = project_A_tasks.union(project_B_tasks)
print("Union:", all_tasks)
diff_tasks = project_A_tasks.difference(project_B_tasks)
print("Difference:", diff_tasks)
sym_diff_tasks = project_A_tasks.symmetric_difference(project_B_tasks)
print("Symmetric Difference:", sym_diff_tasks)
Example 4: Creating an Empty Set
empty_set = set()
print(empty_set) # set()
print(type(empty_set)) # <class 'set'>
empty_dict = {}
print(type(empty_dict)) # <class 'dict'>
Example 5: Looping Through a Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
Example 6.1: Set Comprehension (Numbers)
squared_numbers = {x**2 for x in range(5)}
print("Squared Numbers:", squared_numbers)
Example 6.2: Set Comprehension (Strings)
words = ["apple", "banana", "cherry", "avocado"]
first_letters = {word[0] for word in words}
print(first_letters) # {'a', 'b', 'c'}
Challenge 25
- Create a set of your favorite stocks.
- Add a few more stocks.
- Remove one stock.
- Perform a union with another set.
- Find the common stocks using intersection.
my_stocks = {"AAPL", "TSLA", "AMZN"}
print("Initial:", my_stocks)
my_stocks.add("MSFT")
my_stocks.add("GOOGL")
print("After Adding:", my_stocks)
my_stocks.remove("AMZN")
print("After Removing:", my_stocks)
friend_stocks = {"TSLA", "META", "MSFT", "NFLX"}
all_stocks = my_stocks.union(friend_stocks)
print("Union:", all_stocks)
common_stocks = my_stocks.intersection(friend_stocks)
print("Common Stocks:", common_stocks)
👉 For more tutorials like this, visit my website and don’t forget to subscribe to my YouTube channel: Coding with Subin🚀