Sahaj.blogs
5 Sept 2023 · StudyPhase 1 · Python

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:

  1. Removing duplicates: set(list).
  2. Fast membership tests: x in s is O(1) on average. On a list it’s O(n).

Set algebra:

  • a | b union
  • a & b intersection
  • a - b difference
  • a ^ b symmetric 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: True

#python#data-structures

Sources

  1. Data Structures: sets — Python Software Foundation
  2. Set types: set, frozenset — Python Software Foundation
  3. TimeComplexity (Python wiki) — Python Software Foundation