One of the core Python data types that we did not mention in earlier articles that perhaps deserves some attention is the set. Sets are a recent addition to Python; they are neither mappings (dictionaries) nor sequences (strings, lists and typles). Sets are created by calling the built-in set function or using new set literals and expressions in 3.0, and they support the usual mathematical set operations.
Introduction to Sets
Creating a set can be done two different ways:
>>> mySet = set(‘hello’)
>>> otherSet = {‘a’,’b’,’c’,’d’,’e’}
len returns the number of unique set items, so we get:
>>> len(otherSet)
5
But if we run the same operation on mySet, we get:
>>> len(mySet)
4
>>> ‘h’ in mySet
True
>>> ‘i’ in mySet
False
>>> mySet.isdisjoint(otherSet)
False
>>> newSet = set(‘he’)
newSet.issubset(mySet)
True
Mathematical set operations are generally valid on sets:
>>> mySet, otherSet
({‘o’, ‘e’, ‘l’, ‘h’}, {‘e’, ‘d’, ‘b’, ‘a’, ‘c’})
>>> mySet & otherSet
{‘e’}
>>> mySet | otherSet
{‘e’, ‘h’, ‘o’, ‘d’, ‘b’, ‘c’, ‘a’, ‘l’}
>>> mySet – otherSet
{‘o’, ‘l’, ‘h’}
There are a few other operations. <= tests whether ever element in the left operand set is in the right operand set. For example: >>> newSet <= mySet
True
But what if we want to return False if the sets are equal? Then we use <:
>> newSet < mySet
True
>>> exactcopy = set(mySet)
>>> exactcopy < mySet
False
>>> exactcopy <= mySet
True
We can flip the operand around, and check to see if the left operand set is a superset of the right operand set:
>>> mySet > newSet
True
>>> mySet >= newSet
True
Sets are mutable; you can add and remove items with the add and remove methods:
>>> otherSet.add(‘f’)
{‘e’, ‘f’, ‘d’, ‘b’, ‘c’, ‘a’}
>>> otherSet.remove(‘c’)
>>> otherSet
{‘e’, ‘f’, ‘d’, ‘b’, ‘a’}
You can also iterate over a set. For example:
>>> for s in mySet:
print(s)
o
e
l
h
Since sets are mutable, there are some things we cannot do with them: for example, we cannot use them as dictionary keys. But objects of type frozenset are immutable. Therefore:
>>> unchangeableSet = frozenset(‘abc’)
Although we can’t add and remove items, we can perform the usual set operations on frozensets, or a combination of sets and frozensets:
>>> mySet | unchangeableSet
{‘o’, ‘e’, ‘b’, ‘h’, ‘c’, ‘a’, ‘l’}
For an example of using frozenset to create keys for a dictionary, here’s a sample:
>>> keySet = frozenset(‘abc’)
>>> names = [ ‘Able’, ‘Baker’, ‘Charlie’ ]
>>> myDict = { }
>>> i = 0
>>> for s in keySet:
myDict[s] = names[i]
i += 1
>>> print(myDict)
{‘a’: ‘Able’, ‘b’: ‘Baker’, ‘c’: ‘Charlie’}
Here, we created an immutable set called keySet, and a list of items to put in our dictionary. We iterate through the set, mapping items in the list to keys in keySet. When we print out the results, we see that each item was successfully mapped to a key.
In the next article, we will continue our look at sets.
External Links:
Set, frozenset at docs.python.org – Official documentation on sets and frozensets for Python 3.4
Recent Comments