Python · Syntax · Beginner
Set Methods
Learn how to work with sets: adding and removing elements, and set operations like union, intersection, and difference.
Quick topic start and explanations before exercises (exercises below):
Practical Set Tasks
#Set Methods Reference
#Exercises:
Safe Removal
#Write a function `safe_remove(s, value)` that removes `value` from set `s` if it exists, and returns `True` if it was removed or `False` if it was not found. The function must never raise an error. Example: `s = {1, 2, 3}; safe_remove(s, 2)` → `True`, `s == {1, 3}`; `safe_remove(s, 99)` → `False`.
def safe_remove(s, value):
pass
s = {1, 2, 3}
print(safe_remove(s, 2)) # True (s is now {1, 3})
print(safe_remove(s, 99)) # False
Solution
def safe_remove(s, value):
if value in s:
s.discard(value)
return True
return False
# Or even simpler:
def safe_remove_v2(s, value):
before = len(s)
s.discard(value)
return len(s) < before
s = {1, 2, 3}
print(safe_remove(s, 2)) # True
print(safe_remove(s, 99)) # False
Deduplicate List
#Write a function `unique_ordered(lst)` that removes duplicate elements from a list while preserving the order of first appearances. Example: `unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])` → `[3, 1, 4, 5, 9, 2, 6]`. Use a set to track seen elements.
def unique_ordered(lst):
pass
print(unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [3, 1, 4, 5, 9, 2, 6]
Solution
def unique_ordered(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(unique_ordered([3, 1, 4, 1, 5, 9, 2, 6, 5, 3]))
# [3, 1, 4, 5, 9, 2, 6]
Common Elements
#Write a function `common(a, b)` that returns a set of elements that appear in both lists `a` and `b`. Example: `common([1, 2, 3, 4], [3, 4, 5, 6])` → `{3, 4}`. Convert to sets and use an intersection operation.
def common(a, b):
pass
print(common([1, 2, 3, 4], [3, 4, 5, 6]))
# {3, 4}
Solution
def common(a, b):
return set(a) & set(b)
print(common([1, 2, 3, 4], [3, 4, 5, 6]))
# {3, 4}
Only in One
#Write a function `exclusive(a, b)` that returns a set of elements that appear in exactly one of the two lists (but not both). Example: `exclusive([1, 2, 3], [2, 3, 4])` → `{1, 4}`. Use the symmetric difference operation.
def exclusive(a, b):
pass
print(exclusive([1, 2, 3], [2, 3, 4]))
# {1, 4}
Solution
def exclusive(a, b):
return set(a) ^ set(b)
print(exclusive([1, 2, 3], [2, 3, 4]))
# {1, 4}
Is Subset
#Write a function `is_subset(small, big)` that returns `True` if every element of `small` is also in `big`. Both arguments can be lists or sets. Example: `is_subset([1, 2], [1, 2, 3, 4])` → `True`, `is_subset([1, 5], [1, 2, 3])` → `False`.
def is_subset(small, big):
pass
print(is_subset([1, 2], [1, 2, 3, 4])) # True
print(is_subset([1, 5], [1, 2, 3])) # False
Solution
def is_subset(small, big):
return set(small) <= set(big)
print(is_subset([1, 2], [1, 2, 3, 4])) # True
print(is_subset([1, 5], [1, 2, 3])) # False
Unique Words
#Write a function `unique_word_count(text)` that returns the number of unique words in a text string (case-insensitive). Example: `unique_word_count("The cat sat on the mat the cat")` → `5` (the, cat, sat, on, mat).
def unique_word_count(text):
pass
print(unique_word_count("The cat sat on the mat the cat"))
# 5 (the, cat, sat, on, mat)
Solution
def unique_word_count(text):
return len(set(text.lower().split()))
print(unique_word_count("The cat sat on the mat the cat"))
# 5 (the, cat, sat, on, mat)
Valid Characters
#Write a function `has_only_valid(s, allowed)` that returns `True` if every character in string `s` is contained in the string `allowed`. Example: `has_only_valid("hello", "aehllo")` → `True`, `has_only_valid("hello!", "aehllo")` → `False`. Use set operations.
def has_only_valid(s, allowed):
pass
print(has_only_valid("hello", "aehllo")) # True
print(has_only_valid("hello!", "aehllo")) # False
Solution
def has_only_valid(s, allowed):
return set(s) <= set(allowed)
print(has_only_valid("hello", "aehllo")) # True
print(has_only_valid("hello!", "aehllo")) # False
Set Comprehension
#Write a function `vowel_set(text)` that returns a set of all unique vowels (a, e, i, o, u) that appear in `text` (case-insensitive). Use a set comprehension. Example: `vowel_set("Hello World")` → `{"e", "o"}`.
def vowel_set(text):
pass
print(vowel_set("Hello World")) # {"e", "o"}
print(vowel_set("Python")) # {"o"}
Solution
def vowel_set(text):
vowels = "aeiou"
return {ch for ch in text.lower() if ch in vowels}
print(vowel_set("Hello World")) # {"e", "o"}
print(vowel_set("Python")) # {"o"}
Venn Diagram
#Students can join Club A, Club B, or both. Given two sets `club_a` and `club_b` of student names, write a function `venn(club_a, club_b)` that returns a dict with three keys: `"only_a"` (in A only), `"only_b"` (in B only), `"both"` (in both). Example: `venn({"Alice", "Bob", "Carol"}, {"Bob", "Carol", "David"})` → `{"only_a": {"Alice"}, "only_b": {"David"}, "both": {"Bob", "Carol"}}`.
def venn(club_a, club_b):
pass
result = venn({"Alice", "Bob", "Carol"}, {"Bob", "Carol", "David"})
print(result["only_a"]) # {"Alice"}
print(result["only_b"]) # {"David"}
print(result["both"]) # {"Bob", "Carol"}
Solution
def venn(club_a, club_b):
return {
"only_a": club_a - club_b,
"only_b": club_b - club_a,
"both": club_a & club_b,
}
result = venn({"Alice", "Bob", "Carol"}, {"Bob", "Carol", "David"})
print(result["only_a"]) # {"Alice"}
print(result["only_b"]) # {"David"}
print(result["both"]) # {"Bob", "Carol"}
All Common in Multiple Sets
#Write a function `common_all(*lists)` that returns a set of elements that appear in ALL of the given lists. Example: `common_all([1, 2, 3], [2, 3, 4], [2, 3, 5])` → `{2, 3}`. Handle the case where no lists are given (return empty set).
def common_all(*lists):
pass
print(common_all([1, 2, 3], [2, 3, 4], [2, 3, 5])) # {2, 3}
print(common_all([1, 2], [3, 4])) # set()
print(common_all()) # set()
Solution
def common_all(*lists):
if not lists:
return set()
result = set(lists[0])
for lst in lists[1:]:
result &= set(lst)
return result
print(common_all([1, 2, 3], [2, 3, 4], [2, 3, 5])) # {2, 3}
print(common_all([1, 2], [3, 4])) # set()
print(common_all()) # set()