Skip to content

Sets

A set ({1, 2, 3}) is an unordered collection of unique, hashable items β€” duplicates are automatically discarded. Sets are optimized for fast membership testing (in) and for mathematical set operations like union, intersection, and difference.

fruits = {"apple", "banana", "apple"} # {'apple', 'banana'} -- duplicate dropped
fruits.add("cherry")
fruits.discard("banana") # remove if present, no error if missing
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # union: {1, 2, 3, 4}
print(a & b) # intersection: {2, 3}
print(a - b) # difference: {1}
print(a ^ b) # symmetric difference: {1, 4}
# Fast membership test
print(3 in a) # True -- O(1) average, unlike checking a list

Trying to create an empty set with {} β€” that actually creates an empty dict, not a set, because {} is the dict literal.

empty = {}
print(type(empty)) # <class 'dict'> <- not a set!
empty_set = set()
print(type(empty_set)) # <class 'set'> <- correct way
  1. What happens when you add a duplicate item to a set?

    AnswerNothing changes β€” sets silently ignore additions of items that already exist.
  2. How do you create an empty set?

    Answerset() β€” not {}, which creates an empty dict instead.
  3. Why is checking x in my_set generally faster than x in my_list?

    AnswerSets use a hash table internally, giving average O(1) membership checks, while lists require a linear O(n) scan.