1. Introduction
A set is an unordered collection of unique elements in Python, built on the same hash-table concept as dictionary keys. Sets automatically eliminate duplicate values and provide highly efficient membership testing and mathematical set operations.
Cricket analogy: A set is like a list of players who've ever taken a hat-trick in IPL history — each name hashed and stored once, so even if you try to add "Bumrah" twice, he only appears once, and checking if he's in the list is nearly instant.
Sets are defined using curly braces {} or the set() constructor. Because they are unordered and store only unique, hashable elements, they cannot contain duplicates or be indexed like lists and tuples.
Cricket analogy: You declare the hat-trick club with curly braces like naming squad members at selection, but unlike a fixed batting order (a list), you can't ask "who's third in the set" — there's no slot 3, just membership.
2. Syntax
# Creating sets
empty_set = set() # NOT {} which creates an empty dict
fruits = {"apple", "banana", "apple"}
# Adding and removing
fruits.add("cherry")
fruits.discard("banana")
# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
union = a | b
intersection = a & b
difference = a - b
symmetric_diff = a ^ b
# Membership test
is_present = 2 in a3. Explanation
Sets support classic mathematical operations: union (|), intersection (&), difference (-), and symmetric difference (^). These make sets ideal for tasks like removing duplicates from a collection or comparing two groups of items.
Cricket analogy: Comparing Mumbai Indians' trophy-winning seasons with Chennai Super Kings' using union gives all years either won, intersection gives years both happened to dominate different tournaments, and difference shows years only one franchise won.
Membership testing (x in my_set) is on average O(1) for sets, much faster than the O(n) linear search required for lists, which is why sets are preferred when frequently checking whether an item exists in a large collection.
Cricket analogy: Checking whether "Dhoni" is in the all-time centurions set is instant regardless of how many thousands of players exist, unlike scanning through a full printed scorecard list player by player to find his name.
Sets have no guaranteed order and no indexing — my_set[0] raises TypeError: 'set' object is not subscriptable. Also, {} creates an empty DICTIONARY, not an empty set; use set() to create an empty set.
Because sets automatically discard duplicates, converting a list to a set (set(my_list)) is a common and efficient idiom for deduplicating elements — though it does not preserve the original order.
4. Example
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = set(numbers)
print("unique:", unique_numbers)
a = {1, 2, 3}
b = {2, 3, 4}
print("union:", a | b)
print("intersection:", a & b)
print("difference:", a - b)
try:
print(a[0])
except TypeError as e:
print("TypeError:", e)5. Output
unique: {1, 2, 3, 4}
union: {1, 2, 3, 4}
intersection: {2, 3}
difference: {1}
TypeError: 'set' object is not subscriptable6. Key Takeaways
- Sets store unique, hashable elements with no guaranteed order.
- Use
set()to create an empty set;{}creates an empty dictionary instead. - Sets are not indexable or sliceable —
my_set[0]raises a TypeError. - Set operators
|,&,-,^provide union, intersection, difference, and symmetric difference. - Converting a list to a set is a fast way to remove duplicates, but the original order is not preserved.
- Membership testing with
inis much faster on sets than on lists for large collections.
Practice what you learned
1. What does `{}` create in Python?
2. What is the result of `{1, 2, 2, 3, 3, 3}`?
3. What error does `my_set[0]` raise?
4. Given `a = {1,2,3}` and `b = {2,3,4}`, what does `a & b` return?
5. Which operation would you use to find elements only in set `a` but not in set `b`?
6. Why is membership testing (`x in my_set`) generally faster than `x in my_list`?
Was this page helpful?
You May Also Like
Lists in Python
A mutable, ordered sequence type in Python used to store collections of items, with a deep dive into mutation, aliasing, and common list operations.
Dictionaries in Python
Python's key-value mapping type, covering hashable keys, insertion order guarantees (3.7+), common dict methods, and typical gotchas.
Tuples in Python
An immutable, ordered sequence type in Python, covering tuple syntax, the nested-mutable-element trap, tuple packing/unpacking, and use cases.
List Comprehension in Python
A concise Python syntax for building lists from iterables in a single expression, including conditionals and the memory-difference vs generator expressions.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics