How do you remove an element from a set in Python?

You can use the remove() method of a set to delete a specific element from the set.

The example code is as follows:

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

# 删除集合中的元素
my_set.remove(3)

# 打印集合
print(my_set)

The result of operation is:

{1, 2, 4, 5}

Please note that if the element to be removed is not in the collection, the remove() method will raise a KeyError exception. If you are unsure if the element exists, you can use the discard() method to remove it without raising an exception.

The sample code is as follows:

# 创建一个集合
my_set = {1, 2, 3, 4, 5}

# 删除集合中的元素
my_set.discard(3)

# 打印集合
print(my_set)

The running result is:

{1, 2, 4, 5}

The discard() method does not throw an exception, regardless of whether the element is present in the set or not.

bannerAds