Set
- set is a built-in Python class categorized as a collection data type.
- Stores multiple values (of the same or different types) in a single object, with unique values only.
- Duplicates are automatically removed, making sets ideal for tasks like removing duplicates or performing mathematical set operations (e.g., union, intersection).
- Non-empty set: setobj = {val1, val2, ..., valn}
- Empty set: setobj = set() (Note: {} creates an empty dictionary, not a set).
# non-empty set
var = {1,2,3,4,5}
print(var,type(var))
# empty set
var = {} # dict
print(var,type(var))
var1 = set()
print(var1,type(var1,type(var1))
# duplicate not allowed
var = {1,1,2,2,33,44}
print(var,type(var))
- No Insertion Order: Sets are unordered, so the display order of elements is unpredictable and may vary (e.g., {10, 20, 30} might print as {30, 10, 20}).
- No Indexing/Slicing: Because sets lack order, operations like s1[0] or s1[0:3] raise a TypeError.
- Uniqueness: Sets automatically eliminate duplicates (e.g., {10, 10, 10} becomes {10}).
- Sets are mutable: You can add or remove elements using methods like add(), remove(), or pop().
- However, sets do not support item assignment (e.g., s1[0] = 100 is invalid because sets are unordered).
- Elements within a set must be immutable (e.g., you can include a tuple (1, 2) but not a list [1, 2]).
- Lists: Ordered, mutable, allow duplicates, support indexing/slicing. Example: [10, 10, 20] retains duplicates.
- Tuples: Ordered, immutable, allow duplicates, support indexing/slicing. Example: (10, 10, 20) retains duplicates.
- Sets: Unordered, mutable, no duplicates, no indexing/slicing. Example: {10, 10, 20} becomes {10, 20}.
- Use sets for unique collections or set operations (e.g., finding common students across classes).
- Use lists for ordered, modifiable data (e.g., a list of marks that may change).
- Use tuples for fixed, ordered data (e.g., a student’s record).