Python · Syntax · Beginner

Set Methods

10 tasks

Learn how to work with sets: adding and removing elements, and set operations like union, intersection, and difference.

Set Methods

#
A set is an unordered collection of **unique** elements. Sets are mutable, but elements must be hashable (immutable types like strings, numbers, tuples). Sets do not support indexing — you cannot access `s[0]`. ## Creating sets ```python s = {1, 2, 3} empty = set() # NOT {} — that creates an empty dict! from_list = set([1, 2, 2, 3, 3]) print(from_list) # {1, 2, 3} — duplicates removed automatically ``` ## Adding and removing ```python s = {1, 2, 3} s.add(4) # adds 4 to the set s.add(2) # no effect — 2 already exists print(s) # {1, 2, 3, 4} s.remove(3) # removes 3 — raises KeyError if not found s.discard(99) # removes 99 if present — NO error if not found print(s) # {1, 2, 4} popped = s.pop() # removes and returns an ARBITRARY element print(popped) # some element (sets are unordered) s.clear() # removes all elements print(s) # set() ``` ## Set operations ```python a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union: all elements from both print(a | b) # {1, 2, 3, 4, 5, 6} print(a.union(b)) # same # Intersection: only elements in BOTH print(a & b) # {3, 4} print(a.intersection(b)) # same # Difference: in A but NOT in B print(a - b) # {1, 2} print(a.difference(b)) # same # Symmetric difference: in A or B but NOT both print(a ^ b) # {1, 2, 5, 6} print(a.symmetric_difference(b)) # same ``` ## Subset and superset checks ```python small = {1, 2} big = {1, 2, 3, 4} print(small.issubset(big)) # True — all of small is in big print(small <= big) # same using operator print(big.issuperset(small)) # True — big contains all of small print(big >= small) # same print(small.isdisjoint({5, 6})) # True — no elements in common ``` ## In-place update methods ```python a = {1, 2, 3} a.update({3, 4, 5}) # adds all elements (like |=) print(a) # {1, 2, 3, 4, 5} a.intersection_update({2, 3}) # keeps only elements in both print(a) # {2, 3} a.difference_update({3}) # removes elements in argument print(a) # {2} ```

Practical Set Tasks

#
## Deduplication The most common use case for sets: removing duplicates from a list while keeping one copy of each value. ```python numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] unique = list(set(numbers)) print(sorted(unique)) # [1, 2, 3, 4, 5, 6, 9] ``` Note: converting to set loses the original order. To preserve order while removing duplicates, use a different approach: ```python def deduplicate(lst): seen = set() result = [] for item in lst: if item not in seen: seen.add(item) result.append(item) return result print(deduplicate([3, 1, 4, 1, 5, 9, 2, 6, 5])) # [3, 1, 4, 5, 9, 2, 6] ``` ## Finding common and unique elements ```python team_a = {"Alice", "Bob", "Carol", "David"} team_b = {"Bob", "David", "Eve", "Frank"} # Who is on both teams? both = team_a & team_b print(both) # {"Bob", "David"} # Who is only on team A? only_a = team_a - team_b print(only_a) # {"Alice", "Carol"} # Everyone involved (no duplicates) everyone = team_a | team_b print(everyone) # {"Alice", "Bob", "Carol", "David", "Eve", "Frank"} # Who is on exactly one team? exclusive = team_a ^ team_b print(exclusive) # {"Alice", "Carol", "Eve", "Frank"} ``` ## Checking membership ```python # Set lookup is O(1) — much faster than list for large collections allowed_extensions = {".jpg", ".jpeg", ".png", ".gif", ".webp"} def is_image(filename): _, ext = filename.rsplit(".", 1) if "." in filename else (filename, "") return f".{ext.lower()}" in allowed_extensions print(is_image("photo.jpg")) # True print(is_image("doc.pdf")) # False print(is_image("readme.txt")) # False ``` ## Set comprehension ```python words = ["hello", "world", "hello", "python", "world"] unique_words = {w.lower() for w in words} print(unique_words) # {"hello", "world", "python"} # Unique first letters first_letters = {word[0] for word in ["apple", "banana", "avocado", "cherry"]} print(sorted(first_letters)) # ["a", "b", "c"] ```

Set Methods Reference

#
## Mutating methods | Method | What it does | |---|---| | `s.add(x)` | Add `x` to the set | | `s.remove(x)` | Remove `x` (raises `KeyError` if not found) | | `s.discard(x)` | Remove `x` if present, no error if absent | | `s.pop()` | Remove and return an arbitrary element | | `s.clear()` | Remove all elements | | `s.update(other)` | Add all elements of `other` to `s` | | `s.intersection_update(other)` | Keep only elements in both | | `s.difference_update(other)` | Remove elements found in `other` | ## Set operations — methods and operators | Operation | Method | Operator | Result | |---|---|---|---| | Union | `a.union(b)` | `a | b` | All elements from A and B | | Intersection | `a.intersection(b)` | `a & b` | Only in both A and B | | Difference | `a.difference(b)` | `a - b` | In A, not in B | | Symmetric diff | `a.symmetric_difference(b)` | `a ^ b` | In A or B, not both | | Subset | `a.issubset(b)` | `a <= b` | All of A is in B | | Superset | `a.issuperset(b)` | `a >= b` | A contains all of B | | Disjoint | `a.isdisjoint(b)` | — | A and B share no elements | ## Operators vs methods Operators (`|`, `&`, `-`, `^`) require **both operands to be sets**. Methods (`.union()`, `.intersection()`, etc.) accept **any iterable** as argument: ```python s = {1, 2, 3} s.union([3, 4, 5]) # OK — list accepted s | [3, 4, 5] # TypeError — operator needs a set ``` ## Set comprehension ```python {expr for var in iterable} {expr for var in iterable if condition} ``` ## Common patterns ```python # Deduplicate preserving order seen = set() result = [x for x in lst if not (x in seen or seen.add(x))] # Fast membership test VALID = {"admin", "editor", "viewer"} if role not in VALID: raise ValueError(f"Unknown role: {role}") # Find common elements in multiple sets common = set.intersection(*list_of_sets) ```
01

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
02

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]
03

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}
04

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}
05

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
06

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)
07

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
08

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"}
09

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"}
10

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()