Sets

A set is an unordered collection of zero or more immutable Python data objects. No duplicates are allowed in sets.

Example declaration: mySet = {3,6,"cat",4.5,False}

Useful Operations#

Operation NameOperatorExplanation
membershipinSet membership
lengthlenReturns the cardinality of the set
``aset \| othersetReturns a new set with all elements from both sets
&aset & othersetReturns a new set with only those elements common to both sets
-aset - othersetReturns a new set with all items from the first set not in second
<=aset <= othersetAsks whether all elements of the first set are in the second

Mathematical Operations#

Method NameUseExplanation
unionaset.union(otherset)Returns a new set with all elements from both sets
intersectionaset.intersection(otherset)Returns a new set with only those elements common to both sets
differenceaset.difference(otherset)Returns a new set with all items from first set not in second
issubsetaset.issubset(otherset)Asks whether all elements of one set are in the other
addaset.add(item)Adds item to the set
removeaset.remove(item)Removes item from the set
popaset.pop()Removes an arbitrary element from the set
clearaset.clear()Removes all elements from the set