Collections
Python ships with four core collection types, each with different rules around ordering, mutability, and uniqueness.
fruits = ["apple", "banana", "cherry"] # list: ordered, mutablepoint = (10, 20) # tuple: ordered, immutableprices = {"apple": 1.50, "banana": 0.75} # dict: key-value, ordered (3.7+)unique_tags = {"python", "tutorial", "docs"} # set: unordered, no duplicatesQuick comparison
| Type | Ordered | Mutable | Duplicates | Typical use |
|---|---|---|---|---|
list | Yes | Yes | Allowed | Sequences you’ll modify |
tuple | Yes | No | Allowed | Fixed records, dict keys |
dict | Yes (3.7+) | Yes | Unique keys | Lookups by key |
set | No | Yes | Unique values | Membership tests, dedup |
Membership tests are O(1) for sets and dicts
allowed = {"admin", "editor", "viewer"}"admin" in allowed # O(1) average — fast even for huge setsChecking in on a list is O(n) — it scans every element. If you’re checking membership
repeatedly, converting to a set first is usually worth it.
collections module extras
The standard library’s collections module adds specialized containers on top of these:
from collections import Counter, defaultdict, deque
counts = Counter(["a", "b", "a", "c", "a"]) # {'a': 3, 'b': 1, 'c': 1}grouped = defaultdict(list) # missing keys auto-create an empty listqueue = deque(maxlen=3) # fast appends/pops from both ends