Set Methods

  • This lesson covers commonly used Python set methods and their practical applications.

  • A set method is a built-in function used to add, remove, or update elements in a set.
    It helps to perform operations on set data easily.

add() – Add Single Element

Adds one element to the set.

fruits = {"apple", "banana"}
fruits.add("mango")
print(fruits)
  • Explanation

    • Adds "mango" to the set

    • Duplicate values are ignored

update() – Add Multiple Elements

Adds elements from another set, list, or tuple.

colors = {"red", "blue"}
colors.update(["green", "yellow"])
print(colors)
  • Explanation

    • Multiple items added at once

    • No duplicates allowed

remove() – Remove Specific Element

Removes an element from the set.

nums = {1, 2, 3}
nums.remove(2)
print(nums)

discard() – Remove Element Safely

Removes element if present. No error if element is missing.

nums = {1, 2, 3}
nums.discard(5)
print(nums)

pop() – Remove Random Element

Removes and returns a random element from the set.

items = {"pen", "book", "eraser"}
removed_item = items.pop()
print(removed_item)
print(items)

clear() – Remove All Elements

Removes all elements from the set.

data = {10, 20, 30}
data.clear()
print(data)