Python Sets

3 min read ·

Sets are one of Python’s built-in data types used to store multiple unique values in a single variable. They are unordered, mutable, and unindexed, making them ideal for fast membership testing and removing duplicates.
This topic covers sets from basics to practical usage.

What Is a Set?

A set is a collection that:
  • Stores unique elements only
  • Is unordered
  • Is mutable
  • Does not allow indexing

Set vs List vs Tuple

FeatureListTupleSet
OrderedYesYesNo
Allows duplicatesYesYesNo
MutableYesNoYes
IndexingYesYesNo

Creating Sets

Using Curly Braces {}


Using set() Constructor


Empty Set (Important)

This is NOT a set:

Access Set Items

Sets are unordered, so you cannot access items using indexes.

Check If Item Exists


Add Items to a Set

Add One Item – add()


Add Multiple Items – update()


Remove Items from a Set

remove() – Raises Error if Not Found


discard() – No Error if Not Found


pop() – Removes Random Item


clear() – Remove All Items


Set Length


Join Sets (Set Operations)

Union (| or union())


Intersection (& or intersection())


Difference (- or difference())


Symmetric Difference (^)


Set Comprehension


Frozen Set (Immutable Set)

Cannot modify:

Common Mistakes

Expecting Order in Sets

Order may change.

Using Mutable Items in Set


When to Use Sets

Use sets when:
  • You need unique values
  • Membership checking is frequent
  • Order does not matter
  • Removing duplicates is required
Learn Python Python Sets | Python Course