Collection type
A set is an unordered combination of multiple elements, each element is unique, does not exist of the same type, and each element is an immutable type. It is represented by {}, and the elements are separated by commas. Use {} to create a combined type, or the set function. If it is an empty set, you must use set.
>>> a={'a','b'} >>> a {'a', 'b'} >>> b=set("pypy123") >>> b {'p', '2', 'y', '1', '3'}
Set operator:
S|T returns a new set containing all elements in sets S and T
ST includes elements in set S but not in T
S&T includes elements in both sets S and T
S^T includes non-identical elements in sets S and T
S<=T or S<T returns True/False to judge the subset relationship between S and T
S>=T or S>T returns True/False, judging the inclusion relationship between S and T
Enhanced operator:
S |=T
S -=T
S &= T
S ^=T
Collection processing method:
S.add(x) if x is not in S, add x to S
S.discard(x) removes the element x in S, if x is not in the set, no error is reported
S.remove(x) removes the element x in S, if x is not in the set, a KeyError exception is generated
S.clear() removes all elements in S
S.pop() randomly returns an element of S, updates S, if S is empty, a KeyError exception is generated
S.copy() returns a copy of S
len(S) returns the number of elements in the collection
x in S is in, return True
x not in S does not return True
set(x) converts the x variable to a collection type
>>> b {'2', 'y', '1', '3'} >>> try: while True: print(b.pop(),end="") except: pass 2y13 >>> b set()
Collection type application scenarios:
Inclusion relation comparison: 'p' in {'p','y',123} {'p', 'y'} >= {'p','y',123}
Data deduplication : Convert a list type with repeated elements to a collection type without repeated elements. If you need to use a list type, convert the collection type to a list type
>>> ls=['p', 'y', 'y', 'p', 123] >>> ls ['p', 'y', 'y', 'p', 123] >>> s=set(ls) >>> s {'y', 123, 'p'} >>> It=list(s) >>> It ['y', 123, 'p']