Python / Core Python Fundamentals Interview Questions
What is a Python set and what makes it useful for membership testing?
A set is an unordered collection of unique, hashable objects. Internally it is a hash table, giving O(1) average-case lookup — far faster than scanning a list for large collections. Duplicates are silently dropped on creation.
tags = {'python', 'data', 'python', 'api'} # {'python', 'data', 'api'} # Membership print('python' in tags) # True â O(1) # Add / remove tags.add('ml') tags.discard('api') # no error if missing (unlike .remove()) # Set operations a = {1, 2, 3, 4} b = {3, 4, 5, 6} print(a | b) # union {1, 2, 3, 4, 5, 6} print(a & b) # intersection {3, 4} print(a - b) # difference {1, 2} print(a ^ b) # symmetric diff {1, 2, 5, 6}
The practical win is deduplication. Converting a list to a set and back is the fastest way to remove duplicates when order does not matter: unique = list(set(my_list)). For order-preserving deduplication use dict.fromkeys(my_list) (dicts maintain insertion order since 3.7).
frozenset is the immutable variant — hashable and usable as a dictionary key or element of another set.
More Related questions...