Python 101Free
DATA STRUCTURES

Sets

Unordered collections of unique elements.

SECTION 01

The set model

Two problems that sets solve immediately: checking whether a value is in a collection, and removing duplicates. Adding a duplicate does nothing. Iteration order is not guaranteed (unlike dicts).

There are two main reasons to reach for a set. The first is to deduplicate: set(items) collapses any repeats. The second is to ask "is this thing in this collection?" really quickly. Membership tests with in run in O(1) for sets, versus O(n) for lists.

Like dict keys, set elements must be hashable. Strings, numbers, and tuples are fine. Lists and other sets are not. The empty set literal is set(), since {} already means an empty dict.

python
nums = [1, 2, 2, 3, 1]
unique = set(nums)      # {1, 2, 3}
2 in unique             # True
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in