Skip to content

Set

A set is a built-in data structure in Python and is classified as a type of sequence data structure.

Characteristics

  1. Mutable Sequence
  2. Container Sequence
  3. Eliminate all duplicates
  4. Unordered
  5. Support mathematical operations like union, intersection, difference, and symmetric difference
  6. Use braces {}
  7. Implemented using a hash table, a property also applicable to FrozenSets.
  8. Membership testing is very efficient

Creating a set

Utilizing literal set syntax such as {1, 2, 3} is not only quicker but also enhances readability compared to employing the constructor like set([1, 2, 3]). The constructor approach is slower due to the need for Python to search for the set's constructor, compile a list, and subsequently pass it to the constructor.

creating_set.py
>>> s = {1}
>>> print(f"using {{}} to create: {type(s)}")
>>> print(s)
>>> print(s.pop())
>>> print(s)
>>> g = set([1, 2, 3])
>>> print(f"using {{}} to create: {type(g)}")
>>> print(g)
>>> print(g.pop())
>>> print(g)
using {} to create: <class 'set'>
{1}
1
set()
using {} to create: <class 'set'>
{1, 2, 3}
1
{2, 3}

Set Comprehensions (setcomps)

setcomps.py
>>> from unicodedata import name
>>> setcomp = {chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i),'')}
>>> print(type(setcomp))
>>> print(setcomp)
<class 'set'>
{'±', 'µ', '¬', '¥', '¢', '×', '+', '¶', '°', '#', '$', '£', '©', '=', '®', '¤', '<', '>', '§', '÷', '%'}

Elements Must Be Hashable

Elements within a set must be hashable objects, complete with appropriate implementations of __hash__ and __eq__ methods. It's important to note that the set type itself isn't hashable, preventing the construction of sets with nested set instances. However, FrozenSet is hashable, allowing for the inclusion of frozenset elements within a set.

FrozenSet

A FrozenSet is an immutable variation of a set. Unlike sets, there is no distinct syntax to denote frozenset literals. Instead, they are generated by invoking the constructor.

frozen_set.py
>>> my_frozen = frozenset(range(10))
>>> print(type(my_frozen))
>>> print(my_frozen)
<class 'frozenset'>
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})

Set Operations

Infix Operators

frozen_set.py
>>> a = {1, 2, 3 }
>>> b = {3, 4, 5 }
>>> print(f"UNION of A and B: {a | b}")
>>> print(f"INTERSECTION of A and B: {a & b}")
>>> print(f"DIFFERENCE of A and B: {a - b}")
>>> print(f"SYMMETRIC DIFFERENCE of A and B: {a ^ b}")
UNION of A and B: {1, 2, 3, 4, 5}
INTERSECTION of A and B: {3}
DIFFERENCE of A and B: {1, 2}
SYMMETRIC DIFFERENCE of A and B: {1, 2, 4, 5}

Method List

Python Set documentation for a comprehensive list of set and frozen set methods and operations.

References