100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Python

Sets in Python

An unordered collection of unique, hashable elements in Python, covering set creation, operations, and the no-order/no-duplicates gotcha.

Data StructuresBeginner10 min readJul 7, 2026
Analogies

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

python
# 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 a

3. 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

python
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

text
unique: {1, 2, 3, 4}
union: {1, 2, 3, 4}
intersection: {2, 3}
difference: {1}
TypeError: 'set' object is not subscriptable

6. 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 in is much faster on sets than on lists for large collections.

Practice what you learned

Was this page helpful?

Topics covered

#Python#PythonProgrammingStudyNotes#Programming#SetsInPython#Sets#Syntax#Explanation#Example#StudyNotes#SkillVeris