Sets versus multisets

suggest change

Sets are unordered collections of distinct elements. But sometimes we want to work with unordered collections of elements that are not necessarily distinct and keep track of the elements’ multiplicities.

Consider this example:

>>> setA = {'a','b','b','c'}
>>> setA
{'a', 'c', 'b'}  # order is not guaranteed

By saving the strings 'a', 'b', 'b', 'c' into a set data structure we’ve lost the information on the fact that 'b' occurs twice. Of course saving the elements to a list would retain this information

>>> listA = ['a','b','b','c']
>>> listA
['a', 'b', 'b', 'c']

but a list data structure introduces an extra unneeded ordering that will slow down our computations.

>>> from collections import Counter
>>> counterA = Counter(['a','b','b','c'])
>>> counterA
Counter({'b': 2, 'a': 1, 'c': 1})

Counter is a dictionary where elements are stored as dictionary keys and their counts are stored as dictionary values. Since Python 3.7 it keeps insertion order. The repr above lists items from most common to least common; iteration order is 'a', 'b', 'c'.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents