Set-Python3, set set-python3
The remove () and discard () Methods of set are described.
Function/method name
|
Equivalent Operator |
Description |
All set types |
Len (s) |
|
Set base: number of elements in set s |
Set ([obj]) |
|
Variable set factory function: ojb must support iteration. The set is created by elements in obj. Otherwise, an empty set is created. |
Frozenset ([obj]) |
|
Immutable set factory functions: the execution method is the same as the set () method, but it returns an immutable set. |
|
Obj in s |
Member Testing |
|
Obj not in s |
Non-member test |
|
S = t |
Equivalent test |
|
S! = T |
Non-equivalent test |
|
S & lt; t |
(Strictly) subset Test |
S. issubset (t) |
S & lt; = t |
Subset Test |
|
S> t |
(Strictly) superset Test |
S. issuperset (t) |
S & gt; = t |
Superset Test |
S. union (t) |
S | t |
Merge operations |
S. intersec-tion (t) |
S & t |
Intersection operation |
S. difference (t) |
S-t |
Differential operation |
S. symmetric_fifference (t) |
S ^ t |
Symmetric Difference Operation |
S. copy () |
|
Value assignment operation: returns the (Shortest copy) Copy of s. |
Only applicable to variable sets |
S. update (t) |
S | = t |
(Union) Modification Operation: add members in t to s |
S. intersection_update (t) |
S & = t |
Intersection Modification Operation: only contains members of s and t. |
S. difference_update (t) |
S-= t |
Negative Modification Operation: Only Members belonging to s but not t are included in s. |
S. symmetric_difference _ update (t) |
S ^ = t |
Symmetric differential Modification Operation: s contains only s or only t members. |
S. add (obj) |
|
Add operation: Add obj to s |
S. remove (obj) |
|
Delete operation |
S. discard (obj) |
|
Discard operation: remove () a friendly version. If ojb exists in s, delete it from s. |
S. pop () |
|
Pop operation: Remove and return any value in s. |
S. clear () |
|
Clear operation: Remove all elements in s |
For example:
The following code reports an error because 'l' in row 9th remove () does not exist in the set.
The discard () method does not return an error.
1 # Code based on Python 3.x 2 # _*_ coding: utf-8 _*_ 3 # __Author: "LEMON" 4 5 names = ['lemon','zw','lr', 'lr'] 6 names_set = set(names) 7 8 names_set.discard('lemo') 9 names_set.remove('l')10 # Error: 'lr' is not in names_set11 print(names_set)
The correct code is as follows:
1 # Code based on Python 3.x 2 # _*_ coding: utf-8 _*_ 3 # __Author: "LEMON" 4 5 names = ['lemon','zw','lr', 'lr'] 6 names_set = set(names) 7 8 names_set.discard('lemo') 9 names_set.remove('lr')10 # Error: 'lr' is not in names_set11 print(names_set)
The running result is as follows:
1 {'lemon', 'zw'}