Python Set Exercises
Exercise 1: Create a Set
Task: Create a set with values 1, 2, 3, 4, 5
.
# Your code here
my_set = {1, 2, 3, 4, 5}
print(my_set)
Exercise 2: Add Items to a Set
Task: Add the item 6
to the set {1, 2, 3}
.
s = {1, 2, 3}
s.add(6)
print(s)
Exercise 3: Update Set with Multiple Items
Task: Add multiple items [4, 5, 6]
to {1, 2, 3}
.
s = {1, 2, 3}
s.update([4, 5, 6])
print(s)
Exercise 4: Remove an Item Safely
Task: Remove item 3
from the set. Avoid error if it’s missing.
s = {1, 2, 3}
s.discard(3)
print(s)
Exercise 5: Set Union
Task: Combine {1, 2}
and {2, 3, 4}
.
a = {1, 2}
b = {2, 3, 4}
result = a.union(b)
print(result)
Exercise 6: Set Intersection
Task: Print common elements between {1, 2, 3}
and {2, 3, 4}
.
a = {1, 2, 3}
b = {2, 3, 4}
print(a.intersection(b))
Exercise 7: Set Difference
Task: Print elements in {1, 2, 3}
that are not in {2, 3}
.
a = {1, 2, 3}
b = {2, 3}
print(a.difference(b))
Exercise 8: Symmetric Difference
Task: Print elements in either {1, 2, 3}
or {2, 3, 4}
but not in both.
a = {1, 2, 3}
b = {2, 3, 4}
print(a.symmetric_difference(b))
Exercise 9: Check Subset and Superset
a = {1, 2}
b = {1, 2, 3}
print(a.issubset(b)) # True
print(b.issuperset(a)) # True
Exercise 10: Remove All Elements from a Set
s = {1, 2, 3}
s.clear()
print(s) # Output: set()
Bonus Challenge: Unique Words in a Sentence
Task: Extract all unique words from a sentence.
sentence = "Python is fun and Python is powerful"
unique_words = set(sentence.split())
print(unique_words)
Output
{'fun', 'and', 'is', 'powerful', 'Python'}
Summary Table of Skills Practiced
Skill | Method Used |
---|---|
Create set | {} |
Add single/multiple items | add() , update() |
Remove elements | remove() , discard() , clear() |
Combine sets | union() , update() , ` |
Find common/different items | intersection() , difference() |
Advanced operations | symmetric_difference() , issubset() |