Sets

A set is an unordered collection with no duplicate elements [1].

>>> s = {1, 2, 3}  # NOTE: for an empty set we must use `set()`. `{}` would initialize a `dict`

>>> 1 in s
True
>>> 4 in s
False
>>>

>>> s.add(4)
>>> 4 in s
True

>>> s.add(4)  # `{1, 2, 3, 4}` no duplicates allowed as per definition

>>> s.remove(1)  # {2, 3, 4}
>>> s.remove(1)  # `KeyError: 1`
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
>>> s.discard(1)  # it does not raise even if the element does not exist

Operations

Let's check the complexity of the sets' common operations [2]:

OperationTime ComplexitySpace ComplexitySyntax
Adds.add(val)
Sizelen(s)
Search valueval in s
Delete values.remove(val)
Unions | t
Intersections & t

References