setutils - IndexedSet type¶
The set type brings the practical expressiveness of
set theory to Python. It has a very rich API overall, but lacks a
couple of fundamental features. For one, sets are not ordered. On top
of this, sets are not indexable, i.e, my_set[8] will raise an
TypeError. The IndexedSet type remedies both of these
issues without compromising on the excellent complexity
characteristics of Python’s built-in set implementation.
-
class
boltons.setutils.IndexedSet(other=None)[source]¶ IndexedSetis acollections.MutableSetthat maintains insertion order and uniqueness of inserted elements. It’s a hybrid type, mostly like an OrderedSet, but alsolist-like, in that it supports indexing and slicing.Parameters: other (iterable) – An optional iterable used to initialize the set. >>> x = IndexedSet(list(range(4)) + list(range(8))) >>> x IndexedSet([0, 1, 2, 3, 4, 5, 6, 7]) >>> x - set(range(2)) IndexedSet([2, 3, 4, 5, 6, 7]) >>> x[-1] 7 >>> fcr = IndexedSet('freecreditreport.com') >>> ''.join(fcr[:fcr.index('.')]) 'frecditpo'
Standard set operators and interoperation with
setare all supported:>>> fcr & set('cash4gold.com') IndexedSet(['c', 'd', 'o', '.', 'm'])
As you can see, the
IndexedSetis almost like aUniqueList, retaining only one copy of a given value, in the order it was first added. For the curious, the reason why IndexedSet does not support setting items based on index (i.e,__setitem__()), consider the following dilemma:my_indexed_set = [A, B, C, D] my_indexed_set[2] = A
At this point, a set requires only one A, but a
listwould overwrite C. Overwriting C would change the length of the list, meaning thatmy_indexed_set[2]would not be A, as expected with a list, but rather D. So, no__setitem__().Otherwise, the API strives to be as complete a union of the
listandsetAPIs as possible.