Python Sets & Set Operations

Python Sets & Set Operations Interview Questions

What is a set in Python?
A set is an unordered, mutable collection of unique, hashable elements. Sets are defined using curly braces {} or the set() function. Example: my_set = {1, 2, 3, 4} or my_set = set([1, 2, 3]).
What are the key characteristics of Python sets?
Sets are unordered (no indexing), mutable, contain only unique elements (no duplicates), can contain only hashable (immutable) elements, and support mathematical set operations like union, intersection, and difference.
What is a frozenset in Python?
A frozenset is an immutable version of a set. It's created using frozenset() function and can be used as keys in dictionaries or elements of other sets. Example: frozen = frozenset([1, 2, 3]).
What are the main set operations in Python?
union() or | - all elements from both sets
intersection() or & - common elements
difference() or - - elements in first not in second
symmetric_difference() or ^ - elements in either but not both
issubset() or <= - check if set is subset
issuperset() or >= - check if set is superset
How to remove duplicates from a list using sets?
Convert list to set and back to list: unique_list = list(set(original_list)). Note: This doesn't preserve original order. To preserve order: list(dict.fromkeys(original_list)) or use OrderedDict.
What is set comprehension in Python?
Set comprehension creates sets using syntax similar to list comprehension but with curly braces. Syntax: {expression for item in iterable if condition}. Example: squares = {x**2 for x in range(5)} creates {0, 1, 4, 9, 16}.
What is the difference between add() and update() methods?
add() adds a single element to the set. update() adds multiple elements from an iterable. Example: s.add(5) vs s.update([5, 6, 7]).
What are the main set methods in Python?
add() - add single element
remove() - remove element (raises KeyError if not found)
discard() - remove element (no error if not found)
pop() - remove and return arbitrary element
clear() - remove all elements
copy() - return shallow copy
What is the time complexity of set operations?
add(): O(1) average
remove()/discard(): O(1) average
pop(): O(1)
in operator: O(1) average
union()/intersection(): O(n+m) where n,m are set sizes
Sets use hash tables internally for O(1) average operations.
How to check if two sets are disjoint?
Use the isdisjoint() method which returns True if sets have no elements in common. Example: set1.isdisjoint(set2). Alternatively: len(set1 & set2) == 0.
What is the difference between remove() and discard() methods?
remove(element) removes the element and raises a KeyError if the element is not found. discard(element) removes the element but does nothing (no error) if the element is not found.
How to create an empty set in Python?
Use set() function: empty_set = set(). Don't use empty curly braces {} as that creates an empty dictionary. type({}) returns dict, not set.
What is symmetric difference between sets?
Symmetric difference returns elements that are in either set but not in both. Symbol: ^. Method: symmetric_difference(). Example: {1,2,3} ^ {2,3,4} returns {1,4}.
Can sets contain mutable elements?
No, sets can only contain hashable (immutable) elements. Lists and dictionaries cannot be set elements. However, tuples can be set elements if they contain only hashable items. Example: {(1, 2), (3, 4)} is valid.
How to find common elements between multiple sets?
set1 = {1, 2, 3, 4} set2 = {2, 3, 4, 5} set3 = {3, 4, 5, 6} # Using intersection() method common = set1.intersection(set2, set3) # Returns {3, 4} # Using & operator common = set1 & set2 & set3 # Returns {3, 4}
What is the difference between union() and update()?
union() returns a new set containing elements from both sets without modifying originals. update() modifies the original set in-place by adding elements from another set/iterable. Example: set3 = set1.union(set2) vs set1.update(set2).
How to check if a set is subset or superset of another?
Use issubset() or <= operator to check subset. Use issuperset() or >= operator to check superset. Example: set1.issubset(set2) or set1 <= set2.
What are practical use cases for sets in Python?
1. Removing duplicates from sequences
2. Membership testing (faster than lists)
3. Finding common/different elements between collections
4. Mathematical set operations
5. Eliminating duplicate database queries
6. Finding unique items in large datasets
How to convert between lists, tuples, and sets?
# List to set (removes duplicates) my_set = set(my_list) # Set to list my_list = list(my_set) # Tuple to set my_set = set(my_tuple) # Set to tuple my_tuple = tuple(my_set) # Note: Order may not be preserved in set conversions
What is the difference between set and dictionary?
Set: Unordered collection of unique elements, created with {} or set(), elements are values only
Dictionary: Unordered collection of key-value pairs, created with {}, elements have keys and values
Both use hash tables internally, but sets are like dictionaries with only keys (no values).
Note: Sets are Python's implementation of mathematical sets. They provide O(1) average time complexity for membership tests and other operations due to hash table implementation. Sets are ideal for removing duplicates and performing mathematical set operations. Remember that sets are unordered, so don't rely on element order. Use frozensets when you need immutable sets that can be dictionary keys.
Python Sets & Set Operations Next