Set
A set is a built-in data structure in Python and is classified as a type of sequence data structure.
Characteristics
- Mutable Sequence
- Container Sequence
Eliminate all duplicates- Unordered
- Support mathematical operations like union, intersection, difference, and symmetric difference
- Use braces {}
- Implemented using a hash table, a property also applicable to FrozenSets.
- 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.
>>> 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)
>>> 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.
>>> 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
>>> 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.