Q1. What is a set in Python?
A set is an unordered, mutable collection of unique, hashable elements.
Created with curly braces or set().
Example:
Sets support mathematical operations like union, intersection, difference.
Created with curly braces or set().
Example:
s = {1,2,3,3} Duplicates are automatically removed.Sets support mathematical operations like union, intersection, difference.
Q2. How do you add and remove elements from a set?
Add with add(element).
Remove with remove(element) (raises error if not present) or discard(element) (no error).
Pop removes an arbitrary element.
Clear empties the set.
Example:
Remove with remove(element) (raises error if not present) or discard(element) (no error).
Pop removes an arbitrary element.
Clear empties the set.
Example:
s.add(5)
s.discard(10)
item = s.pop()Q3. What are the common set operations?
Union (| or union()), intersection (& or intersection()), difference (- or difference()), symmetric difference (^ or symmetric_difference()).
They return new sets or modify in-place.
Example:
They return new sets or modify in-place.
Example:
a = {1,2,3}
b = {3,4,5}
print(a | b) # {1,2,3,4,5}
print(a & b) # {3}Q4. What is the difference between set and frozenset?
set is mutable; frozenset is immutable.
frozenset can be used as dictionary keys and as elements of another set.
They support the same methods except those that modify the set.
frozenset can be used as dictionary keys and as elements of another set.
They support the same methods except those that modify the set.
Q5. Can a set contain lists? Why or why not?
No, sets require hashable elements.
Lists are mutable and unhashable, so they cannot be stored in a set.
You can use tuples (immutable) instead.
Lists are mutable and unhashable, so they cannot be stored in a set.
You can use tuples (immutable) instead.
