Python · Sets
Sets for uniqueness and fast membership tests, plus union, intersection and difference.
A set is an unordered collection of unique, hashable items. I use sets for two things:
- Removing duplicates:
set(list). - Fast membership tests:
x in sis O(1) on average. On a list it’s O(n).
Set algebra:
a | buniona & bintersectiona - bdifferencea ^ bsymmetric difference (items in exactly one of the two)
{} is an empty dict. For an empty set, write set(). frozenset is an immutable set, so it can be a dict key.
import timeit
python_course = {"Asha", "Ravi", "Sahaj", "Meet"}
cpp_course = {"Ravi", "Sahaj", "Dev"}
print(sorted(python_course & cpp_course)) # both
print(sorted(python_course - cpp_course)) # only python
print(sorted(python_course ^ cpp_course)) # exactly one
print(type({}).__name__, type(set()).__name__)
nums = list(range(100_000))
s = set(nums)
t_list = timeit.timeit(lambda: 99_999 in nums, number=200)
t_set = timeit.timeit(lambda: 99_999 in s, number=200)
print("set is faster:", t_set < t_list)
Output:
['Ravi', 'Sahaj']
['Asha', 'Meet']
['Asha', 'Dev', 'Meet']
dict set
set is faster: TrueSources
- Data Structures: sets — Python Software Foundation
- Set types: set, frozenset — Python Software Foundation
- TimeComplexity (Python wiki) — Python Software Foundation