dev.rean.me
python

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

Share:

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


๐Ÿ“š Related Post

โ† Back to python
Share: