The sets module provides classes for constructing and manipulating unordered collections of unique elements but is deprecated since version 2.6 and is replaced by the build-in `set` and `frozenset` types.

Table of Contents

# 1. sets, set and frozenset

The sets module provides classes for constructing and manipulating unordered collections of unique elements but is deprecated since version 2.6 and is replaced by the build-in `set` and `frozenset` types.

class set([iterable]) # Return a new set object whose elements are taken from iterable. class frozenset([iterable]) # Return a new frozenset object whose elements are taken from iterable. # The elements of a set must be hashable. # To represent sets of sets, the inner sets must be frozenset objects.

# 2. Basic operations

Instances of `set` and `frozenset` provide the following operations:

len(s) # Return the cardinality of set s. x in s # Test x for membership in s. x not in s # Test x for non-membership in s. isdisjoint(other) # Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. issubset(other) set <= other # Test whether every element in the set is in other. set < other # set <= other and set != other. issuperset(other) set >= other # Test whether every element in other is in the set. set > other # set >= other and set != other. union(other, ...) set | other | ... # Return a new set with elements from the set and all others. intersection(other, ...) set & other & ... # Return a new set with elements common to the set and all others. difference(other, ...) set - other - ... # Return a new set with elements in the set that are not in the others. symmetric_difference(other) set ^ other # Return a new set with elements in either the set or other but not both. copy() # Return a new set with a shallow copy of s.

3. intersection of a list of sets

>>> list_sets = [set([1, 2, 3]), set([2, 3, 4]), set([3, 4, 5])] >>> set.intersection(*list_sets) # Note that set.intersection is different from set().intersection set([3]) # BTW, convert a list of lists to a list of sets by: list_sets = [set(row) for row in lists]

3. frozenset

The following table lists operations available for `set` that do not apply to immutable instances of `frozenset`:

微信赞赏支付宝赞赏