Sets
Python - A Quick Start for existing Programers
2 min read
Published Sep 16 2025, updated Sep 30 2025
Guide Sections
Guide Comments
A set is a built-in unordered, mutable collection of unique elements.
- Think of it like a mathematical set.
- Duplicates are automatically removed.
- Sets are mutable, but elements must be hashable (immutable types) like numbers, strings, or tuples of immutables.
Examples:
Sets don't support accessing by an index value, you only have the option to see if a value is in a set:
Built-in Functions for Sets
The following built in functions work with sets:
len(s)→ number of elements in the setmin(s)→ smallest element (if ordering is defined)max(s)→ largest elementsum(s)→ sum of elements (only works if numeric)sorted(s)→ returns a new list of elements in sorted orderany(s)→Trueif any element is truthyall(s)→Trueif all elements are truthy
Examples:
Modifying sets
Function | Description |
| Add a single element to the set |
| Add multiple elements from one or more iterables |
| Remove element; raises |
| Remove element if present; no error if missing |
| Remove and return an arbitrary element |
| Remove all elements from the set |
Examples:
Set Operations and relations
Sets allow you to compare the contents of two sets, to show the similarities or differences between the two sets.

Examples of operations (all these methods have a shorthand version too using |, &, -, ^):
Examples of relations:
Casting to a set
Convert an iterable into a set to remove duplicates and allow set operations, works with:
- List
- Tuple
- String
- Dictionary - keys only
Examples:
Set Comprehension
- Syntax is almost the same as list comprehension, but with
{}instead of[]. - Produces a set → unordered, unique elements, no duplicates.
- Useful for deduplication, filtering, and transformations where order doesn’t matter.
- Order is not guaranteed.
Syntax:
Examples:














