Skip to content

Module 8 · Python Data Structures — topic 12 of 22

Sets

Sets are unordered collections of unique items with very fast membership tests. Learn how to create sets (including the empty set), add and remove items, and what can be stored in a set.

Beginner 10 min read·Lesson 115 of 306 in Python Programming

Learning objectives

  • Create sets and remove duplicates with set()
  • Add and remove items with add, discard and remove
  • Explain hashability and why sets are fast

Definition

Sets are unordered collections of unique items with very fast membership tests. Learn how to create sets (including the empty set), add and remove items, and what can be stored in a set.

Introduction

A set is a collection of unique items with no particular order. Adding an item that is already present has no effect. Sets are written with braces: {"python", "java"}.

Why it matters

Sets answer “have I seen this before?” and “what are the distinct values?” better than any other structure. Removing duplicate emails, tracking visited pages or checking whether a word is in a vocabulary of thousands are natural set tasks.

Detailed explanation

Sets keep only one copy of each value: set([3, 1, 3, 2]) is {1, 2, 3}.

Sets are unordered: they have no indexes and no slicing, and the printed order isn’t guaranteed. Use sorted(s) to get a list in order.

{} creates an empty dictionary, not a set. Use set() for an empty set.

add(x) inserts an item; discard(x) removes it if present without error; remove(x) removes it but raises KeyError if absent; pop() removes an arbitrary item; clear() empties the set.

Items must be hashable, which in practice means immutable: numbers, strings and tuples of immutable values are fine, but lists and dictionaries can’t be set members.

Sets use hashing to find items, so x in a_set is fast even with millions of items, whereas x in a_list checks items one by one.

frozenset is an immutable version of a set that can itself be a set member or dictionary key.

Syntax

Python
tags = {"python", "beginner"}
empty = set()
unique = set(items)
tags.add("loops")
tags.discard("java")
  • Braces with values make a set.
  • set() makes an empty set; {} is a dict.
  • add and discard change the set.

Code examples

Uniqueness

Python
emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
unique = set(emails)
print(len(emails), len(unique))
print(sorted(unique))
print(type({}).__name__, type(set()).__name__)
Output
5 3
['a@x.com', 'b@x.com', 'c@x.com']
dict set

Adding and removing

Python
seen = {"home"}
seen.add("about")
seen.add("home")
seen.discard("blog")
print(sorted(seen))
try:
seen.remove("blog")
except KeyError:
print("remove() raises KeyError for a missing item")
Output
['about', 'home']
remove() raises KeyError for a missing item

More examples

Tracking first-time visitors

Python
visits = ["u1", "u2", "u1", "u3", "u2", "u4", "u1"]
seen = set()
first_visits = []
for user in visits:
if user not in seen:
seen.add(user)
first_visits.append(user)
print("Unique visitors:", len(seen))
print("Order of first visits:", first_visits)
try:
bad = {[1, 2]}
except TypeError as err:
print("TypeError:", err)
print({(1, 2), (1, 2), (2, 1)} == {(1, 2), (2, 1)})
Output
Unique visitors: 4
Order of first visits: ['u1', 'u2', 'u3', 'u4']
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
True

Step-by-step explanation

  • seen is checked before adding, so each user is recorded once.
  • first_visits keeps the order in which new users appeared, which a set alone can’t do.
  • A list can’t be a set member because it is mutable (unhashable).
  • Tuples are hashable, and duplicate tuples collapse to one.

Expected output

Running “Tracking first-time visitors” prints exactly:

TextOutput
Unique visitors: 4
Order of first visits: ['u1', 'u2', 'u3', 'u4']
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
True

Practical applications

  • Web analytics count unique visitors with sets.
  • Spell checkers test words against a set of known words.
  • Crawlers keep a set of visited URLs to avoid loops.

Best practices

  • Use sets for uniqueness and fast membership.
  • Use discard() when the item may be absent.
  • Sort a set before displaying it.

Common mistakes

Creating an empty set with {}

Avoid

tags = {}
tags.add("x")

Prefer

tags = set()
tags.add("x")

{} is an empty dictionary, which has no add method.

Indexing a set

Avoid

first = tags[0]

Prefer

first = sorted(tags)[0]

Sets have no order or indexes.

Key takeaways

  • Sets hold unique, hashable items in no particular order.
  • set() is an empty set; {} is an empty dict.
  • add, discard, remove and pop change a set; in is fast.

Try it yourself

  1. 1
    Count the distinct words in a sentence using a set (ignore case).
  2. 2
    Given two lists of roll numbers, check quickly whether a given roll number is in either.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic