19. How to Use Sets in Python with Examples (Video in Khmer)
Learn Python sets with simple examples. Add and remove items, use set methods, and compare sets.
2026-10-25 ยท 3 min read
Hello friend! ๐ A set keep unique items. It remove duplicate items for you. Set items have no fixed order.
In this post, I show you how to create and use sets in Python. Easy and short. ๐
๐งบ Create a Set
Use curly brackets {} to make a set. Duplicate values only appear one time.
colors = {"red", "blue", "red"}
print(colors) # {'red', 'blue'} (order can be different)
Use set() to make an empty set. {} make an empty dictionary, not a set.
empty_set = set()
๐ฅ Video: Introduction to Sets and Methods in Python (Khmer)
โ Add and Remove Items
Use .add() to add one item. Use .discard() to remove an item. It do not give an error if item is missing.
fruits = {"apple", "banana"}
fruits.add("mango")
fruits.discard("banana")
print(fruits) # {'apple', 'mango'} (order can be different)
๐ Check for an Item
Use in to check if a set has an item.
fruits = {"apple", "banana"}
print("apple" in fruits) # True
print("mango" in fruits) # False
๐ Set Operations
Set operations help compare groups.
a = {"apple", "banana"}
b = {"banana", "mango"}
print(a | b) # Union: all items
print(a & b) # Intersection: items in both
print(a - b) # Difference: items in a, not b
Output (order can be different):
{'apple', 'banana', 'mango'}
{'banana'}
{'apple'}
๐ฅ Video: Set Operations in Python (Khmer)
๐ Remove Duplicates from a List
Make a set from a list to remove duplicate values. Set order is not fixed.
numbers = [1, 2, 2, 3, 3]
unique_numbers = set(numbers)
print(unique_numbers) # {1, 2, 3} (order can be different)
โ Common Error
Sets do not have item positions. Do not use an index:
colors = {"red", "blue"}
# print(colors[0]) # TypeError
Use a loop to get each item:
for color in colors:
print(color)
๐ก Tips
- A set keep each item one time only.
- Set order can change. Do not depend on item order.
- Use
set()to make an empty set. - Use
.add()to add an item. - Use
.discard()to remove an item without error if it is missing. - Use
|,&, and-for union, intersection, and difference. - Use a set when you need unique values, not positions.
โ Any Question?
Tell us in comment below! ๐
#Python #Set #SetMethods #LearnPython #Beginner