sec02 - Python set Methods Explained

In this lecture, we will introduce five commonly used methods of Python’s set type.

スポンサーリンク

Overview of Set Editing and Methods

Since sets do not preserve order, you cannot change values by specifying an index as you would with a list. Likewise, methods that reference indexes, such as list.index(), are not available.

The operations available for sets are as follows:

  • Adding elements without specifying an index... add(), update()
  • Removing elements by specifying a value... remove(), discard()
  • Removing elements without a defined order... pop()
  • Union, intersection, difference, and symmetric difference (| & - ^)

How to Use the add() Method and Key Points

add() adds a single element to the set.

s = {1, 2}
s.add(3)  # Add one element
print(s)  # {1, 2, 3}

You can also add a tuple, as shown below. In that case, the tuple itself will be added as a single element.

Unlike the update() method, which we will cover next, the elements of the tuple will not be unpacked and added individually.

s = {1, 2}
s.add((3, 4))  # Add a tuple
print(s)       # {1, 2, (3, 4)}
スポンサーリンク

How to Add Multiple Elements with the update() Method

update() takes an iterable (such as a list, tuple, or set) as its argument. The elements of the argument are unpacked and added to the set.

s = {1, 2}
s.update([3, 4, 5])  # list
print(s)             # {1, 2, 3, 4, 5}

s = {1, 2}
s.update((3, 4, 5))  # tuple
print(s)             # {1, 2, 3, 4, 5}

s = {1, 2}
s.update({3, 4, 5})  # set
print(s)             # {1, 2, 3, 4, 5}

Differences Between remove() and discard()

Both remove() and discard() remove an element specified by its value.

remove() raises a KeyError if the specified element does not exist, whereas discard() does not raise an error.

If you want to detect errors, use remove(). If it does not matter whether the specified element was actually removed, use discard().

s = {1, 2}
s.remove(2)  # Remove an element (raises KeyError if not found)
print(s)

s = {1, 2}
s.discard(2)  # Remove an element (no error even if not found)
print(s)

How to Extract Elements with the pop() Method

pop() removes and returns one element from the set, but the element is chosen in an arbitrary order.

Since sets do not preserve order, the result depends on the environment. Therefore, you should write code assuming that the order of extracted elements may differ between testing and production environments.

s = {1, 2}
result = s.pop()  # Remove and return one element (order is arbitrary)
print(s)       # {2}
print(result)  # 1
スポンサーリンク