"Author's Homepage": Shibie Sanri wyx
"Author's Profile": CSDN top100, Alibaba Cloud Blog Expert, Huawei Cloud Share Expert, Network Security High-quality Creator
"Recommended Column": Xiaobai Zero Basic "Python Beginner to Master"
Detailed explanation of remove function
remove() can "delete" the specified "element" in the collection
grammar
set.remove( element )
parameter
- element : (required) the element to be deleted
return value
- None, no return value, only modify the original array.
Example: delete the specified element in the collection
set1 = {
1, 2, 3, 4, 5}
set1.remove(2)
print(set1)
output:
{
1, 3, 4, 5}
From the pseudo-source code (Python’s built-in functions cannot see the source code, only the description of the function), we can see that remove() can “delete” an element; but this element must “exist” , and if it does not exist, an error will be reported KeyError
1. Delete multiple elements
remove() only accepts "one parameter" , which means that only "one element" can be deleted at a time ; deleting multiple elements will report an error TypeError: remove() takes exactly one argument
set1.remove(1, 2)
However, we can cooperate with "loop" to delete "small collections" in the collection
set1 = {
1, 2, 3, 4, 5, 6}
set2 = {
1, 2, 3}
for i in set2:
set1.remove(i)
print(set1)
output:
{
4, 5, 6}
2. Deleting elements that do not exist will report an error
When remove() deletes "non-existent" elements in the collection , an error will be reported KeyError
set1 = {
1, 2, 3, 4, 5}
set1.remove(6)
output:
3. The deleted element can be of any type
The elements removed by remove () can be "any type" , provided that the collection can store this type, such as integers, strings, and tuples.
set1 = {
1, 'str', (1, 2)}
set1.remove(1)
set1.remove('str')
set1.remove((1, 2))
print(set1)
output:
set()
4. What is the difference between remove() and discard()?
remove() and discard() are used in the same way, both can delete the specified element in the collection, but remove() will report an error when deleting an element that does not exist, while discard() will not report an error.
When you are not sure whether the element exists in the collection, use discard()
set1 = {
1, 2, 3}
set1.discard(9)
print(set1)
output:
{
1, 2, 3}
When it is determined that the element exists in the collection, use remove()
set1 = {
1, 2, 3}
set1.remove(9)
print(set1)
output:
Traceback (most recent call last):
File "C:\Users\dell\PycharmProjects\pythonProject1\test1.py", line 3, in <module>
set1.remove(9)
KeyError: 9