Set is a built-in Python data type used to store a collection of unique items.
- Stores only unique elements; duplicate values are automatically removed.
- Unordered collection, so elements do not have a fixed position and cannot be accessed using indexes.
- Supports fast search, insertion and deletion operations using hashing internally.
Example: This example shows how to create a set with some numbers and check its type.
s = {10, 50, 20}
print(s)
print(type(s))
Output
{10, 50, 20}
<class 'set'>
Note: There is no specific order for set elements to be printed
Type Casting
set() method is used to convert other data types, such as lists or tuples, into sets.
s = set(["a", "b", "c"])
print(s)
Output
{'b', 'a', 'c'}
Check unique and Immutable
Sets cannot have duplicate values. While you cannot modify the individual elements directly, you can still add or remove elements from the set.
# a set cannot have duplicate values
s = {"Geeks", "for", "Geeks"}
print(s)
# values of a set cannot be changed
s[1] = "Hello"
print(s)
Output
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment
Explanation:
- s = {"Geeks", "for", "Geeks"} duplicates are removed, only unique values remain.
- s[1] = "Hello" Error, set elements cannot be changed directly. Only add() or remove() can modify a set.
Heterogeneous Element
Sets can store heterogeneous elements in it, i.e., a set can store a mixture of string, integer, boolean, etc datatypes.
s = {"Geeks", "for", 10, 52.7, True}
print(s)
Output
{True, 52.7, 'Geeks', 10, 'for'}
Frozen Sets
Frozenset is an immutable version of a set. Its elements cannot be changed after creation, but you can perform operations like union, intersection and difference. Use frozenset() to create one.
s = set(["a", "b", "c"])
print("Normal Set:", s)
fs = frozenset(["e", "f", "g"])
print("Frozen Set:", fs)
Output
('Normal Set:', set(['a', 'c', 'b']))
('Frozen Set:', frozenset(['e', 'g', 'f']))
Note: Frozensets are immutable, so methods like add() or remove() cannot be used. They are also hashable, which allows them to be used as dictionary keys.
Internal working of Set
Python sets use a hash table to store unique elements and perform insertion, deletion, and lookup efficiently. Python calculates a hash value to determine each element's initial position in the table.
- Insertion: Checks whether an equal element already exists. If not, the element is added to an available slot.
- Collision Handling: If two elements map to the same position, CPython uses open addressing with probing to find another suitable slot.
- Lookup: Uses the hash value to locate the element and check for a match.
- Deletion: Marks the removed slot with a special dummy marker to ensure that searches for other elements continue correctly.
Methods for Sets
1. Adding elements: add() function is used to insert new elements into a set. It automatically ignores duplicates.
s = {"a", "b", "c"}
s.add("d")
print(s)
Output
{'c', 'd', 'a', 'b'}
2. Union: union() function combines two sets and returns a new set with all unique elements.
a = {"x", "y"}
b = {"y", "z"}
u = a.union(b)
print(u)
Output
{'z', 'y', 'x'}
3. Intersection: intersection() function returns a new set containing elements that are common to both sets.
a = {1, 2, 3}
b = {2, 3, 4}
i = a.intersection(b)
print(i)
Output
{2, 3}
4. Difference: difference() function returns a set containing elements that are in the first set but not in the second.
a = {1, 2, 3}
b = {2, 3, 4}
d = a.difference(b)
print(d)
Output
{1}
5. Clear: clear() function removes all elements from a set, leaving it empty.
s = {1, 2, 3}
s.clear()
print(s)
Output
set()
Operators for Sets
Sets and frozen sets support the following operators:
| Operators | Notes |
|---|---|
| key in s | containment check |
| key not in s | non-containment check |
| s1 == s2 | s1 is equivalent to s2 |
| s1 != s2 | s1 is not equivalent to s2 |
| s1 <= s2 | s1 is subset of s2 |
| s1 < s2 | s1 is proper subset of s2 |
| s1 >= s2 | s1 is superset of s2 |
| s1 > s2 | s1 is proper superset of s2 |
| s1 | s2 | the union of s1 and s2 |
| s1 & s2 | the intersection of s1 and s2 |
| s1 - s2 | the set of elements in s1 but not s2 |
| s1 ˆ s2 | the set of elements in precisely one of s1 or s2 |