🐍 Python Beginner

What are Python sets?

Answer

A Python set is an unordered collection of unique, hashable elements — duplicates are automatically removed. Create: {1, 2, 3} or set([1, 1, 2, 3]){1, 2, 3}. Create empty: set() (not {}, which creates an empty dict). Operations: add(), remove() (KeyError if missing), discard() (no error if missing), pop() (removes arbitrary element). Set operations: | union, & intersection, - difference, ^ symmetric difference, <= subset check. Membership test is O(1) (hash-based): 3 in my_set. frozenset is an immutable set (hashable, can be a dict key or set element). Use sets for deduplication, fast membership testing, and set algebra operations.