The method and difference between set and frozenset in python

The difference between set (variable collection) and frozenset (immutable collection):

The set is sorted out of order and not repeated, it is variable, and has methods such as add() and remove(). Since it is mutable, it does not have a hash value. Basic functions include relationship testing and elimination of duplicate elements. Collection objects also support mathematical operations such as union (union), intersection (intersection), difference (difference set) and sysmmetric difference (symmetric difference set).
sets supports x in set, len(set), and for x in set. As an unordered collection, sets do not record element positions or insertion points. Therefore, sets do not support indexing, or other sequence-like operations.
Frozenset is a frozen collection, which is immutable and has a hash value. The advantage is that it can be used as the key of a dictionary or as an element of other collections. The disadvantage is that once created, it cannot be changed, there is no add, remove method.

1. Collection creation

The set() and frozenset() factory functions are used to generate mutable and immutable sets, respectively. If no arguments are provided, the default
will generate an empty collection. If an argument is provided, it must be an iterable, that is, a sequence, or iterator, or support
An object to iterate over, eg a list or a dictionary.

>>> s=set('cheeseshop') #Use the factory method to create
>>> s
{'h', 'c', 'o', 's', 'e', 'p'}
>>> type(s)
<type 'set'>
 
>>> s={'chessseshop','bookshop'}# Create directly, similar to [] of list and {} of dict, what is different from dict is the value in it, set will convert the elements in it for tuples
>>> s
{'bookshop', 'chessseshop'}
>>> type(s)
<type 'set'>
 
# Immutable collection creation:
>>> t=frozenset('bookshop')
>>> t
frozenset({'h', 'o', 's', 'b', 'p', 'k'})

2. Update mutable collection

Members of collections are added and removed using various collection built-in methods and operators:

>>> s.add('z') #Add
>>> s
set(['c', 'e', 'h', 'o', 'p', 's', 'z'])
>>> s.update('pypi') #add
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y' , 'z'])
>>> s.remove('z') #delete
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y' ])
>>> s -= set('pypi')#delete
>>> s
set(['c', 'e', 'h', 'o', 's'])
>>> del s #delete collection

Only mutable collections can be modified. Attempting to modify an immutable collection will throw an exception.

>>> t.add('z')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'frozenset' object has no attribute 'add'

3. Membership (in, not in)

 >>> 'k' in s
 False
 >>> 'k' in t
 True
 >>> 'c' not in t
 True

Fourth, set equivalence/inequality

>>> s == t
False
>>> s != t
True
>>> u = frozenset(s)
>>> s == u
True
>>> set('posh') == set('shop')
True

5. Subset/Superset

 >>> set('shop') < set('cheeseshop')
 True
 >>> set('bookshop') >= set('shop')
 True

6. Traversing and accessing the values in the collection (both mutable and non-mutable collections are supported)

>>> s=set('cheeseshop')
>>> s
{'h', 'c', 'o', 's', 'e', 'p'}
>>> for i in s:
    print(i)
h
c
o
the s
e
p
 
 
>>> t=frozenset('bookshop')
>>> t
frozenset({'h', 'o', 's', 'b', 'p', 'k'})
>>> for i in t:
    print(i)
h
o
the s
b
p
k

Seven, collection type operators (all collection types)

1. Joint ( | )

The union of two sets is a new set in which every element is a member of at least one of the sets, that is, a member of one of the two sets. Union symbols have an equivalent method, union().

 >>> s | t
 set(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's' ])

2. Intersection ( & amp; )

You can compare the intersection operation to the AND (or conjunction) operation of sets. The intersection of two sets is a new set, each element of which is a member of both sets at the same time, that is, is a member of both sets. The intersection notation has an equivalent method, intersection()

>>> s & t
set(['h', 's', 'o', 'p']

3. Difference complement/relative complement ( – )

The difference or relative complement of two sets (s and t) refers to a set C whose elements only belong to the set s, not to the set t. Difference symbols have an equivalent method, difference().

>>> s - t
set(['c', 'e'])

4. Symmetrical difference ( ^ )

Like other Boolean set operations, symmetric differencing is the XOR (aka “exclusive OR”) of sets.
The symmetric difference of two sets (s and t) refers to another set C. The elements in this set can only be members of set s or set t, and cannot belong to both sets at the same time. Symmetric difference has an equivalent method, symmetric_difference().

>>> s ^ t
set(['k', 'b', 'e', 'c'])

5. Mixed collection type operations
In the above example, s on the left is a mutable collection, while t on the right is an immutable collection. Note that the set operation operator above is still a mutable collection, but if the order of the left and right operands is reversed, the result It’s different:

>>>t | s
frozenset(['c', 'b', 'e', 'h', 'k', 'o', 'p', 's' ])
>>> t ^ s#Python Xiaobai learning exchange group: 711312441
frozenset(['c', 'b', 'e', 'k'])
>>> t - s frozenset(['k', 'b'])

If the types of the left and right operands are the same, both mutable sets or immutable sets, the resulting type is the same, but if the types of the left and right operands are not the same (the left operand is set, the right operand is frozenset, or vice versa), the result produced is of the same type as the left operand.

VIII. Methods of variable collection types

s.update(t) modifies s with elements from t, i.e., s now contains members of either s or t
s.intersection_update(t) The members in s are the elements that belong to both s and t.
s.difference_update(t) members in s are elements that belong to s but are not contained in t
s.symmetric_difference_update(t) update members in s to those contained in s or t, but not s
elements common to t
s.add(obj) adds object obj to collection s
s.remove(obj) removes the object obj from the collection s; if obj is not an element in the collection s (obj not
in s), a KeyError will be raised
s.discard(obj) deletes the object obj from the set s if obj is an element in the set s;
s.pop() deletes any object in the collection s and returns it
s.clear() deletes all elements in the collection s

9. Collection type operators, functions and methods

Function/Method Name Equivalence Operator Description
All collection types:

len(s) set cardinality: the number of elements in set s
set([obj]) Mutable set factory function; obj must be iterable, defined by obj
elements to create a collection, otherwise create an empty collection
frozenset([obj]) immutable set factory function; the implementation is the same as the set() method,
but it returns an immutable collection
obj in s membership test: is obj an element in s?
obj not in s non-membership test: is obj not an element in s?
s == t equivalence test: Tests whether s and t have the same elements?
s != t inequality test: opposite of ==
s < t (strictly speaking) subset test; s != t and all in s
The elements of are all members of t
s.issubset(t) s <= t subset test (subsets allowed in a looser sense): all elements in s
are all members of t
s > t (strictly speaking) superset test: s != t and all elements in t
are all members of s
s.issuperset(t) s >= t superset test (allow superset in a loose sense): all elements in t
are all members of s
s.union(t) s | t union operation: elements in s or t
s.intersec-tion(t) s & amp; t intersection operation: elements in s and t
s.difference(t) s - t difference operation: elements in s, not elements in t
s.symmetric_difference(t) s ^ t symmetric difference operation: elements in s or t, but not common to s and t
Elements
s.copy() copy operation: returns a (shallow copy) copy of s

For mutable collections only:

s.update(t) s |= t (Union) Modification operation: add members in t to s
s.intersection_update(t) s & amp;= t intersection modification operation: s only includes members common to s and t
s.difference_update(t) s -= t difference update operation: s includes members that only belong to s but not to t
s.symmetric_
difference_
update(t) s ^= t Symmetric differential modification operation: s includes only s or only t
member
s.add(obj) plus operation: add obj to s
s.remove(obj) delete operation: remove obj from s; if it does not exist in s
obj, will raise KeyError
s.discard(obj) discard operation: friendly version of remove() - as in
If obj exists in s,
remove it from s
s.pop() Pop operation: remove and return any element in s
s.clear() Clear operation: remove all elements in s