Python Data Structures: Lists, Tuples, Dicts and Sets
Python has four built-in collection types you will use every day: list, tuple, dict and set. Picking the right one makes code shorter, clearer and often much faster. This page explains what each is for, what its common operations cost, and the mistakes that trip people up. Examples use Python 3.10 or later.
The short version
| Type | Literal | Ordered | Mutable | Duplicates | Use it for |
|---|---|---|---|---|---|
list | [1, 2, 3] | Yes | Yes | Yes | A sequence you add to, remove from or reorder |
tuple | (1, 2) | Yes | No | Yes | A fixed group of values, such as a point or a record |
dict | {"a": 1} | Insertion order | Yes | Keys unique | Looking up a value by a key |
set | {1, 2} | No | Yes | No | Membership tests and removing duplicates |
Note that {} is an empty dict, not an empty set; write set() for that.
Lists
tasks = ["write tests", "fix bug"]
tasks.append("deploy") # add to the end
tasks.insert(0, "read issue") # add at a position (shifts the rest)
print(tasks)
print(tasks[0], tasks[-1]) # index from the start and the end
print(tasks[1:3]) # a slice is a new list
last = tasks.pop() # remove from the end
print(last, len(tasks))
print("fix bug" in tasks) # linear search
Output:
['read issue', 'write tests', 'fix bug', 'deploy']
read issue deploy
['write tests', 'fix bug']
deploy 3
True
A list is a dynamic array: items sit next to each other in memory, so reading tasks[i] is instant at any position, and adding to the end is cheap. Inserting or removing at the front is slow on a long list, because every later item has to move along one place. Searching with in checks the items one by one.
Tuples
point = (3, 4)
x, y = point # unpacking
print(x, y)
def min_max(values):
return min(values), max(values) # returns a tuple
low, high = min_max([7, 2, 9])
print(low, high)
distances = {(0, 0): "origin", (3, 4): "five away"} # tuples can be dict keys
print(distances[(3, 4)])
try:
point[0] = 10
except TypeError as err:
print("TypeError:", err)
Output:
3 4
2 9
five away
TypeError: 'tuple' object does not support item assignment
Use a tuple when the number and meaning of the items is fixed: coordinates, an RGB color, a function returning two values. Because tuples cannot change, they can be dict keys and set members (as long as their contents are immutable too); lists cannot. When the fields deserve names, typing.NamedTuple or a dataclass reads better than record[2].
Dictionaries
ages = {"ada": 36, "grace": 85}
ages["linus"] = 21 # add or update
print(ages["ada"])
print(ages.get("alan")) # None instead of KeyError
print(ages.get("alan", 0)) # or a default of your choice
for name, age in ages.items(): # insertion order is preserved
print(name, age)
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
Output:
36
None
0
ada 36
grace 85
linus 21
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
A dict is a hash table: Python hashes the key to find where the value lives, so lookup, insert and delete take about the same time whether the dict holds ten items or ten million. Keys must be hashable (strings, numbers, tuples of those); values can be anything. Since Python 3.7, dicts keep keys in the order they were inserted, as a language guarantee.
ages["alan"] raises KeyError: 'alan' when the key is missing. Use ages.get("alan") when absence is normal, and ages["alan"] when absence is a bug you want to hear about.
Sets
emails = ["a@example.com", "b@example.com", "a@example.com"]
unique = set(emails)
print(len(unique))
allowed = {"read", "write"}
print("delete" in allowed) # fast membership test
backend = {"python", "sql", "git"}
frontend = {"javascript", "css", "git"}
print(sorted(backend & frontend)) # in both
print(sorted(backend | frontend)) # in either
print(sorted(backend - frontend)) # only in backend
Output:
2
False
['git']
['css', 'git', 'javascript', 'python', 'sql']
['python', 'sql']
A set is a dict with keys and no values. Membership tests are fast, duplicates disappear, and the operators &, | and - give intersection, union and difference. Sets have no order you can rely on, which is why the example wraps them in sorted() before printing. Converting a list to a set removes duplicates but loses the order; list(dict.fromkeys(items)) removes duplicates and keeps the first-seen order.
What operations cost
Big O notation describes how an operation's cost grows with the number of items, n. O(1) means it does not grow; O(n) means it grows in proportion to n. These figures come from the Python documentation's time complexity of built-in types page:
| Operation | list | dict / set (average) |
|---|---|---|
| Read or write by index / key | O(1) | O(1) |
| Add at the end / add a key | O(1) amortized | O(1) amortized |
| Remove from the end | O(1) | n/a |
| Insert or remove at the front | O(n) | n/a |
| Delete a key | n/a | O(1) |
x in container | O(n) | O(1) |
| Sort | O(n log n) | n/a |
"Amortized" means an individual append is occasionally slow, when the storage has to grow, but the average over many appends stays constant. The dict and set figures are averages that assume keys hash well; in the worst case, when many keys collide, those operations become O(n).
The practical consequence: if you test membership inside a loop, the container matters. Checking each of n items against a list of n items is O(n²) work in total, roughly n times n comparisons; checking against a set is O(n). Converting the list to a set once, before the loop, is often the single biggest speedup available in beginner code.
Three helpers from collections
from collections import Counter, defaultdict, deque
words = "the cat and the hat and the bat".split()
print(Counter(words).most_common(2))
by_letter = defaultdict(list)
for word in words:
by_letter[word[0]].append(word)
print(dict(by_letter))
queue = deque(["job1", "job2"])
queue.append("job3") # O(1) at the right end
print(queue.popleft()) # O(1) at the left end; list.pop(0) is O(n)
print(queue)
Output:
[('the', 3), ('and', 2)]
{'t': ['the', 'the', 'the'], 'c': ['cat'], 'a': ['and', 'and'], 'h': ['hat'], 'b': ['bat']}
job1
deque(['job2', 'job3'])
Countercounts hashable items and finds the most common ones.defaultdict(list)creates an empty list the first time a key is used, which removes the "is the key there yet?" check when grouping.dequeis a double-ended queue with O(1) appends and pops at both ends. Use it for queues instead oflist.pop(0). For a priority queue, see theheapqmodule.
Mistakes that cause bugs
Building a grid with *
grid = [[0] * 3] * 3 # three references to ONE inner list
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(3)] # three separate lists
grid[0][0] = 1
print(grid)
Output:
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0] * 3] * 3 repeats a reference to the same inner list three times, so changing one row changes all of them. Use a list comprehension so each row is a new list.
Removing items while looping over the same list
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n) # changes the list while looping over it
print(nums) # one 2 survived
nums = [1, 2, 2, 3, 4]
odds = [n for n in nums if n % 2 != 0] # build a new list instead
print(odds)
Output:
[1, 2, 3]
[1, 3]
Removing an item shifts the rest left, so the loop skips the item after each removal. Build a new list with a comprehension, or loop over a copy (for n in nums[:]). Changing a dict's size while iterating over it raises RuntimeError: dictionary changed size during iteration.
Other common slips
- Using a list as a dict key or set member, which raises
TypeError: unhashable type: 'list'. Convert it to a tuple. - Expecting a set to keep insertion order. It does not; a dict does.
- Assuming
b = acopies a list. It creates a second name for the same list; see Python basics and data types for how copying works.
Sorting is the next building block; sorting algorithms and Big O explains how sorted() works and why it is O(n log n).