Python Sets

1. What is a Set?

A set is a collection of items that is:

  • Unordered

  • No duplicate values

  • Changeable

In simple words:
👉 A set stores unique values only.

2. Creating a Set

Sets are written using curly brackets { }.

Example

fruits = {"apple", "banana", "orange"}
print(fruits)

3. Duplicate Values Are Not Allowed

Example

numbers = {1, 2, 2, 3, 3}
print(numbers)

Output:

{1, 2, 3}

4. Set is Unordered

Items have no fixed order.

Example

colors = {"red", "blue", "green"}
print(colors)

Output order may change.

5. Access Set Items (Using Loop)

You cannot access items by index.

Example

for color in colors:
print(color)

6. Check Item Exists

Example

print("blue" in colors)

7. Add Items to a Set

Add One Item (add())

fruits.add("mango")
print(fruits)

Add Multiple Items (update())

fruits.update(["grape", "papaya"])
print(fruits)

8. Remove Items from a Set

Remove Item (remove())

fruits.remove("banana")

❌ Error if item not found.

Remove Safely (discard())

fruits.discard("banana")

Remove Random Item (pop())

item = fruits.pop()
print(item)

9. Set Length

Example

print(len(fruits))

10. Join Sets

Union (|)

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)

Intersection (&)

print(a & b)

Difference (-)

print(a - b)

11. Set Methods (Common)

Method Use
add() Add one item
update() Add many items
remove() Remove item
discard() Remove safely
clear() Remove all items

12. Common Beginner Mistakes

❌ Creating Empty Set Wrong Way

s = {}

This creates a dictionary.

✔ Correct:

s = set()

❌ Using Index

print(fruits[0])

❌ Error.

13. Simple Practice Examples

Example 1: Unique Numbers

nums = [1, 2, 2, 3]
unique = set(nums)
print(unique)

Example 2: Check Membership

names = {"Amit", "Ravi", "Sita"}
print("Ravi" in names)

Example 3: Remove Duplicates

data = [10, 20, 20, 30]
data = list(set(data))
print(data)

14. Summary (Python Sets)

✔ Stores unique values
✔ No duplicate allowed
✔ Unordered
✔ No index access
✔ Useful for removing duplicates

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Set Methods (full)

  • Set Exercises

  • Dictionaries (easy)

  • Dictionary Exercises

Just tell me 😊

You may also like...