1. Definition and Basics
In python, a set is a sequence of non-repeating elements, a set is similar to a dictionary, but contains only keys and no associated values.
To create a set, you need to provide a list or tuple as an input set. Such as: s = set([1,2,3]), s=set((1,2,3))
set automatically filters duplicate elements, probably the most common use is to remove duplicate elements from a sequence.
>>> l =[1,2,3,4,5,6,2,4,1]
>>> l
[1, 2, 3, 4, 5, 6, 2, 4, 1]
>>> s =set(l)
>>> s
set([1, 2, 3, 4, 5, 6])
>>>
2, the function of the set
>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__',
'__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__',
'__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__',
'__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear',
'copy', 'difference', 'difference_update', 'discard', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove',
'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>>
s.add(x): You can add element x to the set. Such as: s.add(4)
s.remove(x): remove element x by remove. Such as: s.remove(4)
s.pop(): delete the first element in the set
s.discard(x): discard element x
s.copy(): copy set
s.clear(): delete all elements in the set
set([1, 2, 3, 4, 5, 6])
>>> s.add(10)
>>> s
set([1, 2, 3, 4, 5, 6, 10])
>>> s.pop()
1
>>> s
set([2, 3, 4, 5, 6, 10])
>>> s.remove(10)
>>> s
set([2, 3, 4, 5, 6])
>>> s.union()
set([2, 3, 4, 5, 6])
>>> s.discard(6)
>>> s
set([2, 3, 4, 5])
>>>
>>> s.copy()
set([2, 3, 4, 5])
>>> s
set([2, 3, 4, 5])
>>> s.clear()
>>> s
set([])
A set can be thought of as a collection of unordered and non-repeating elements in the mathematical sense. Therefore, two sets can do intersection and union operations in the mathematical sense.
For example: s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
Intersection: s1 & s2 Union
: s1 | s2
>>> s1 = set([1,2,3])
>>> s2 =set((2,3,4))
>>> s1
set([1, 2, 3])
>>> s2
set([2, 3, 4])
>>> s1 & s2
set([2, 3])
>>> s1 | s2
set([1, 2, 3, 4])
>>>