← Back to Chapters

Python Set Methods

? Python Set Methods

? Quick Overview

Python set is an unordered collection of unique, mutable elements. Set methods help you:

  • Add or remove elements dynamically.
  • Combine sets and find common or different elements.
  • Check relationships between sets (subset, superset, disjoint).

? Handy for membership tests, uniqueness checks, and fast set operations.

? Key Concepts

  • Uniqueness: A set cannot contain duplicate elements.
  • Unordered: The order of elements is not guaranteed (no indexing).
  • Mutable container: You can add or remove elements using methods like add(), remove(), etc.
  • Set operations: Methods like union(), intersection(), and difference() perform mathematical set operations.
  • Relationship checks: Methods like issubset(), issuperset(), and isdisjoint() compare sets.

? Use Cases

  • Removing duplicates from a list by converting it to a set.
  • Finding common users, tags, or IDs between two datasets.
  • Checking if a group of items is fully contained inside another group.
  • Ensuring membership tests like x in my_set are efficient.

? Syntax and Theory

A basic set is created using curly braces {} or the set() constructor:

? Basic Set Creation
numbers = {1, 2, 3, 4}
fruits = {"apple", "banana", "cherry"}

# Using set() constructor
mixed = set([1, 2, 2, 3, "hello"])
print(mixed)  # duplicates removed, order may vary

Python provides several built-in set methods. Common ones:

  • add(x) – Add a single element x to the set.
  • update(iterable) – Add multiple elements from an iterable (list, tuple, set, etc.).
  • remove(x) – Remove element x; raises KeyError if not present.
  • discard(x) – Remove element x if present; does nothing if absent.
  • pop() – Remove and return a random element.
  • clear() – Remove all elements from the set.
  • union(other) – Return a new set with elements from both sets.
  • intersection(other) – Return a new set with common elements.
  • difference(other) – Return elements present in the first set but not the second.
  • isdisjoint(other)True if the sets share no elements.
  • issubset(other)True if all elements of this set are in other.
  • issuperset(other)True if this set contains all elements of other.

? Code Examples

➕ Adding Elements: add() and update()

Use add() for a single item and update() for multiple items from any iterable.

? View Example: add() and update()
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)  # {'apple', 'banana', 'cherry'} (order may vary)

fruits.update(["orange", "kiwi"])
print(fruits)  # {'apple', 'banana', 'cherry', 'orange', 'kiwi'} (order may vary)

? Removing Elements: remove(), discard(), pop(), clear()

remove() raises an error if the item is missing, while discard() silently ignores it. pop() removes and returns a random element, and clear() empties the set.

? View Example: remove(), discard(), pop(), clear()
fruits = {"apple", "banana", "cherry", "orange", "kiwi"}

# remove() - raises KeyError if element not present
fruits.remove("banana")
print(fruits)  # 'banana' removed

# discard() - safe remove, no error if element is missing
fruits.discard("mango")  # No error even though 'mango' is not in the set
print(fruits)

# pop() - removes and returns a random element
item = fruits.pop()
print("Removed:", item)
print("After pop:", fruits)

# clear() - remove all elements
fruits.clear()
print(fruits)  # set()

? Set Operations: union(), intersection(), difference()

These methods correspond to mathematical set operations.

? View Example: union(), intersection(), difference()
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# union() - elements from both sets
print(set1.union(set2))        # {1, 2, 3, 4, 5}

# intersection() - common elements
print(set1.intersection(set2)) # {3}

# difference() - elements in set1 but not in set2
print(set1.difference(set2))   # {1, 2}

? Relationship Checks: isdisjoint(), issubset(), issuperset()

These methods compare two sets and return True or False based on their relationship.

? View Example: isdisjoint(), issubset(), issuperset()
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# isdisjoint() - True if no common elements
print(set1.isdisjoint({6, 7}))     # True
print(set1.isdisjoint(set2))       # False (they share 3)

# issubset() - True if all elements are contained in another set
print({1, 2}.issubset(set1))       # True
print({1, 4}.issubset(set1))       # False

# issuperset() - True if set1 contains all elements of another set
print(set1.issuperset({1, 2}))     # True
print(set1.issuperset({1, 2, 4}))  # False

? Output and Explanation

? What to Notice

  • When printing a set like {'apple', 'banana', 'cherry'}, the element order may change each run, because sets are unordered.
  • After remove("banana"), the element "banana" will no longer appear in the set. Trying fruits.remove("mango") would raise a KeyError.
  • discard("mango") does nothing if "mango" is not in the set, and no error is raised.
  • pop() removes a random element; you will see a different value printed sometimes.
  • union() returns a new set that combines elements from both sets without duplicates.
  • intersection() shows only the common elements (e.g. {3} for {1,2,3} and {3,4,5}).
  • difference() is directional: set1.difference(set2) may be different from set2.difference(set1).
  • issubset(), issuperset(), and isdisjoint() always return booleans (True / False) describing how two sets relate.

✅ Tips and Best Practices

  • Use intersection() to quickly find common elements between two collections.
  • Use difference() to see what is in one set but not in another (e.g. missing permissions, missing IDs).
  • Use issubset() and issuperset() to check if one group of items is fully contained inside another.
  • isdisjoint() is useful for confirming that two sets share no overlap (e.g. two non-overlapping user groups).
  • Remember that sets are unordered; do not rely on the printed order of elements.
  • Avoid using list-only methods like append() on sets; they are not supported.

? Try It Yourself

  • Create two sets (e.g. students_a and students_b) and try all set methods on them.
  • Experiment with pop() a few times to see which element is removed and how it changes the set.
  • Check subset, superset, and disjoint relationships between different sets you create.
  • Use difference() and intersection() on overlapping sets to understand how elements move between the results.
  • Convert a list with duplicate items into a set to remove duplicates, then convert it back to a list.