Python – Set Exercises

Exercise 1: Create a Set

Question

Create a set of fruits and print it.

Solution

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

Exercise 2: Remove Duplicate Values

Question

Remove duplicates from a list using a set.

Solution

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

Exercise 3: Check Item Exists

Question

Check if "banana" is in the set.

Solution

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

Exercise 4: Add Item to Set

Question

Add "mango" to the set.

Solution

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

Exercise 5: Add Multiple Items

Question

Add "grape" and "papaya" to the set.

Solution

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

Exercise 6: Remove Item from Set

Question

Remove "apple" from the set.

Solution

fruits.remove("apple")
print(fruits)

Exercise 7: Remove Item Safely

Question

Remove "kiwi" safely (without error).

Solution

fruits.discard("kiwi")
print(fruits)

Exercise 8: Loop Through Set

Question

Print all items using a loop.

Solution

for fruit in fruits:
print(fruit)

Exercise 9: Join Two Sets

Question

Join two sets.

Solution

a = {1, 2}
b = {2, 3}

result = a.union(b)
print(result)

Exercise 10: Find Common Items

Question

Find common items from two sets.

Solution

print(a.intersection(b))

Exercise 11: Find Difference

Question

Find items in first set but not in second.

Solution

print(a.difference(b))

Exercise 12: Clear a Set

Question

Remove all items from the set.

Solution

fruits.clear()
print(fruits)

Exercise 13: Count Items in Set

Question

Count how many items are in the set.

Solution

print(len(fruits))

Exercise 14: Check Subset

Question

Check if {1, 2} is subset of {1, 2, 3}.

Solution

x = {1, 2}
y = {1, 2, 3}

print(x.issubset(y))

Exercise 15: Check Disjoint Sets

Question

Check if two sets have no common items.

Solution

a = {1, 2}
b = {3, 4}

print(a.isdisjoint(b))

✅ Summary

✔ Sets store unique values
✔ No duplicate allowed
✔ Use methods to add and remove
✔ Union and intersection are useful
✔ Practice improves understanding

📘 Perfect for Beginner eBook

This exercise chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Dictionary Basics (easy)

  • Dictionary Methods

  • Dictionary Exercises

  • Mini Python Projects

Just tell me 😊

You may also like...