Python Set Exercises | Practice Questions with Answers

Python Set Exercises

Solve the following 20 Python set exercises to strengthen your understanding of set operations and methods. Click the "Show Answer" button to view the solution for each question.

1. Create a set named fruits with elements 'apple', 'banana', and 'cherry'.
fruits = {'apple', 'banana', 'cherry'}
print(fruits)
2. Add the element 'orange' to the fruits set.
fruits.add('orange')
print(fruits)
3. Remove 'banana' from the fruits set using remove() method.
fruits.remove('banana')
print(fruits)
4. Remove 'grapes' from the fruits set using discard() method.
fruits.discard('grapes')  # No error even if 'grapes' not present
print(fruits)
5. Create two sets: A = {1, 2, 3} and B = {3, 4, 5}. Find their union.
A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B))
6. Find the intersection of sets A and B.
print(A.intersection(B))
7. Find the difference of set A from set B (elements in A but not in B).
print(A.difference(B))
8. Find the symmetric difference of sets A and B.
print(A.symmetric_difference(B))
9. Check if {1, 2} is a subset of set A.
print({1, 2}.issubset(A))
10. Check if set A is a superset of {2, 3}.
print(A.issuperset({2, 3}))
11. Check if sets A and B are disjoint.
print(A.isdisjoint(B))
12. Clear all elements from set A.
A.clear()
print(A)
13. Create a copy of set B and add element 6 to the copy without changing original.
C = B.copy()
C.add(6)
print('Original B:', B)
print('Copy C:', C)
14. Use update() to add elements {6, 7} to set B.
B.update({6, 7})
print(B)
15. Remove and print an arbitrary element from set B using pop().
elem = B.pop()
print('Popped:', elem)
print('Remaining:', B)
16. Find the length of set B.
print(len(B))
17. Check if element 4 is in set B.
print(4 in B)
18. Iterate over elements of set B and print each.
for elem in B:
    print(elem)
19. Create a set of vowels and check if it's a subset of set {'a', 'e', 'i', 'o', 'u', 'x'}.
vowels = {'a', 'e', 'i', 'o', 'u'}
check_set = {'a', 'e', 'i', 'o', 'u', 'x'}
print(vowels.issubset(check_set))
20. Create an empty set and add elements 1 to 5 using a loop.
s = set()
for i in range(1, 6):
    s.add(i)
print(s)