Table of Contents

3. [0] Sets

Sets are implemented as hash table of (unordered) objects, therefore sets are good for get/set/delete/searching items and bad for . Sets do not support indexing, slicing, or other sequence-like behavior.


In [ ]:
a = {1, 2, 'a', (1, 2)}
a

In [ ]:
print(type(a))

In [ ]:
help(a)

3.2. [0] Sets can grow (O(1))


In [ ]:
a.add('a')
print(a)

3.3. [0] Sets can not contain dupplicate objects


In [ ]:
a.add('a')
print(a)

3.4. [1] Sets can not contain mutable objects

Mutable objects can not be hashed :-(


In [ ]:
a = set()
a.add([1,2]) # Sets can not contain lists

In [ ]:
a = set() # Empty set
a.add({1,2,3}) # Sets can not contain sets

3.5 [0] Intersection of sets (O(min(len(s), len(t)))


In [ ]:
a = {1,2,3}
b = {2,3,4}
a.intersection(b)

3.6 [0] Union of sets (O(len(s)+len(t)))


In [ ]:
a.union(b)

3.7. [0] Sets are MUCH more efficient for searching by content than lists


In [ ]:
a = set(range(1000))
print(a)

In [ ]:
%timeit '0' in a

In [ ]:
a = list(range(1000))
print(a)

In [ ]:
%timeit '0' in a