Python sets are a built-in data type used to store an unordered collection of unique elements. They are ideal for tasks like removing duplicates from data, performing fast membership testing, and executing mathematical set operations.
Creation: Use curly braces
{}for non-empty sets (e.g.,my_set = {1, 2, 3}) or theset()constructor for empty sets or conversions from other iterables (e.g.,set([1, 2, 2])→{1, 2}).Key Properties:
No duplicates: Automatically removes repeated values.
Unordered: Elements have no fixed position; order may vary between runs.
Unindexed: Cannot access elements by index or key.
Mutable: Can add or remove elements after creation.
Hashable elements only: Only immutable types (e.g., integers, strings, tuples) can be stored; lists or dictionaries are not allowed.
Common Operations:
Add/Remove: Use
add()to add an element,remove()(raises error if missing), ordiscard()(safe removal).Set Math: Use
union(),intersection(),difference(), andsymmetric_difference()for mathematical operations.Membership Testing: Use
inornot infor O(1) lookup speed, much faster than lists.
Important Note: Use
set()to create an empty set—{}creates an empty dictionary, not a set.
Sets are especially powerful for performance-critical operations involving uniqueness and fast lookups.