Sets are collections of objects without any order. Sets are mutable but cannot contain mutable objects. An example of a set is given below:
Sets are enclosed in braces and can store any immutable objects.
S={'a','b','hello',12,(1,2,3)}
print S
The cardinality of a set can be checked using 'len':
print len(S)
Since a list is mutable, it cannot be a member of a cell:
notS={[1,2,3]}
Whereas a tuple can be:
okS={tuple([1,2,3])}
print okS
Sets don't contain duplicate members:
anotherS={'a','b','a'}
print anotherS
Answer: Try it!
Hint: Sets do not allow repeats!
Let's have a set:
S=set(tuple(range(10)))
print S
Membership testing:
print 0 in S
print -1 not in S
Subsets:
S.isdisjoint({13,14})
S.issubset({1,2,3}) #Check if S is a subset of {1,2,3}
S.issubset(set(tuple(range(100))))
S<=set(tuple(range(100))) #Same as issubset above
S<set(tuple(range(100))) #Proper subset test i.e., set <= other and set != other
T=S.union({-1,-2}) #Equivalent operator: set | other I ...
print T
T=S.intersection({-1,0,1}) #Equivalent operator: set & other & ...
print T
T=S.difference([-1,0,1,2]) #Equivalent operator: set - other - ...
print T
T=S.symmetric_difference([-1,0,1,2]) #Equivalent operator: set ^ other. Returns elements that are in either set but not both.
print T
Note that in the above two examples, we passed a list. All the above functions accept any 'iterable' as an argument but their operator counter parts will operate only on sets to avoid unexpected results from operations such as set('abc') & 'cbs'. For more details see Python documentation on sets.
There are multiple ways of updating a set:
S.update([-2,-1]) #Same as union. You can also use S|={-2,-1}.
print S
Other operators can also be used similarly.
Elements can be added or removed to a set using 'add' or 'remove'.
S.add(100)
print S
S.remove(-1)
print S
'remove(elem)' raise a KeyError exception if the element is not contained in the set.
S.remove(1000)
'discard' does the same as 'remove' without raising any exception in case the element is not found.
S.discard(1000)
'pop' removes and returns an arbitrary element from the set and raises KeyError if the set is empty.
while(1):
print S
print S.pop()
'clear' removes all elements from the set. Note that S={} will not make S empty because {} is a dictionary. If you want to create an empty set use:
S=set()
Python also offers immutable sets which are called 'frozenset's.