Review and test your knowledge of Python sets with comprehensive questions and answers. Practice set operations, membership, and manipulation to strengthen your Python programming skills. Ideal for beginners and students preparing for exams or interviews.
- Sets are unordered collections of unique elements - They are mutable but can only contain immutable (hashable) elements - Unlike lists, sets don't allow duplicates and don't maintain order - Unlike dictionaries, sets don't have key-value pairs - Sets are optimized for membership tests (x in set) - They support mathematical set operations like union, intersection
- "Creating: `s = {1, 2, 3}` or `s = set([1, 2, 3])`" - "Membership test: `2 in s` returns `True`" - "Operations: `s1 | s2` (union), `s1 & s2` (intersection)"
- union(): Returns a new set containing elements from both sets without modifying originals - update(): Modifies the original set by adding elements from another set (in-place operation) - union() can take any iterable while update() takes any iterable - union() is similar to | operator, update() is similar to |= operator
- "union(): `s3 = s1.union(s2)` or `s3 = s1 | s2`" - "update(): `s1.update(s2)` or `s1 |= s2`"
- Frozen sets are immutable versions of regular sets - Created using frozenset() constructor - They are hashable so can be used as dictionary keys or elements of other sets - Useful when you need an immutable collection of unique items - Support all set operations except those that modify the set
- "Creating: `fs = frozenset([1, 2, 3])`" - "As dictionary key: `d = {fs: 'value'}`"
- Set comprehension creates sets using similar syntax to list comprehension - Uses curly braces {} instead of square brackets [] - Results in a set (unique, unordered elements) instead of a list - Can include conditions like list comprehension - Syntax: `{expression for item in iterable if condition}`
- "Basic: `{x**2 for x in range(10)}`" - "With condition: `{x for x in 'abracadabra' if x not in 'abc'}`"
- remove(x): Removes element x, raises KeyError if x not found - discard(x): Removes element x if present, does nothing if not found - pop(): Removes and returns an arbitrary element, raises KeyError if empty - remove() is for when you want to know if element was missing - discard() is for safe removal when you don't care if element exists - pop() is useful for processing elements when order doesn't matter
- "remove(): `s.remove(2)`" - "discard(): `s.discard(3)`" - "pop(): `elem = s.pop()`"
Tutorials, Roadmaps, Bootcamps & Visualization Projects