Lesson 282 of 296
Python data structures
What you will learn
- Lists, tuples, dicts and sets
- Slicing
- Comprehensions
- Mutability and copying
- The mutable default argument trap
- collections: Counter, defaultdict, deque, and heapq
On this page
Lists
A list is an ordered, changeable sequence, like a TypeScript array.
nums = [3, 1, 2]
nums.append(5) # add to the end
nums.insert(0, 9) # insert at index 0
last = nums.pop() # remove and return the last item
nums.sort() # sorts in place, returns None
print(nums, last) # [1, 2, 3, 9] 5
print(len(nums), sum(nums), max(nums), 3 in nums) # 4 15 9 True
print(sorted([3, 1, 2], reverse=True)) # [3, 2, 1] (returns a new list)Trick question: nums.sort() returns None. Writing nums = nums.sort() loses your list. Use sorted(nums) when you want a new list.
Slicing
list[start:stop:step]; stop is not included. Works on lists, tuples and strings.
letters = ["a", "b", "c", "d", "e"]
print(letters[1:3]) # ['b', 'c']
print(letters[:2]) # ['a', 'b']
print(letters[-2:]) # ['d', 'e']
print(letters[::2]) # ['a', 'c', 'e']
print(letters[::-1]) # ['e', 'd', 'c', 'b', 'a'] (reversed copy)
print("hello"[::-1]) # ollehTuples
A tuple is an ordered sequence that cannot change (immutable). Use it for fixed groups of values, like a TypeScript tuple type.
point = (3, 4)
x, y = point # unpacking
print(x + y) # 7
a, b = 1, 2
a, b = b, a # swap without a temporary variable
print(a, b) # 2 1Dictionaries
A dict stores key-value pairs, like a TypeScript object used as a map, or a Map. Keys must be hashable (strings, numbers, tuples; not lists). Dicts keep insertion order.
ages = {"sam": 30, "ana": 25}
ages["leo"] = 41 # add or update
print(ages["sam"]) # 30
print(ages.get("zoe")) # None (ages["zoe"] would raise KeyError)
print(ages.get("zoe", 0)) # 0 (default)
print("ana" in ages) # True (checks keys)
for name, age in ages.items():
print(name, age)
del ages["leo"]
print(list(ages.keys()), list(ages.values())) # ['sam', 'ana'] [30, 25]Sets
A set holds unique values with fast membership checks.
seen = {1, 2, 3}
seen.add(2) # no effect, already there
print(seen) # {1, 2, 3}
print({1, 2, 3} & {2, 3, 4}) # {2, 3} intersection
print({1, 2} | {2, 3}) # {1, 2, 3} union
print({1, 2, 3} - {2}) # {1, 3} difference
print(len(set([1, 1, 2, 2]))) # 2 (remove duplicates)
empty = set() # {} is an empty DICT, not a set
print(type(empty), type({}))Comprehensions
A comprehension builds a list, dict or set in one line. It replaces many map and filter uses.
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums] # [1, 4, 9, 16, 25]
evens = [n for n in nums if n % 2 == 0] # [2, 4]
lengths = {word: len(word) for word in ["hi", "hello"]} # {'hi': 2, 'hello': 5}
unique_mods = {n % 3 for n in nums} # {0, 1, 2}
print(squares, evens, lengths, unique_mods)Mutability and copying
Lists, dicts and sets are mutable. Like objects in JavaScript, assigning does not copy; both names point to the same object.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3] a changed too
c = a.copy() # shallow copy (also: list(a) or a[:])
c.append(4)
print(a, c) # [1, 2, 3] [1, 2, 3, 4]
import copy
nested = [[1], [2]]
deep = copy.deepcopy(nested)
deep[0].append(99)
print(nested) # [[1], [2]] unchangedThe mutable default argument trap
A classic interview question. Default values are created once, when the function is defined, not on every call.
def add_item_bad(item, items=[]):
items.append(item)
return items
print(add_item_bad("a")) # ['a']
print(add_item_bad("b")) # ['a', 'b'] surprise: the same list is reused
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']collections and heapq
The standard library has ready-made structures that appear in many interview solutions.
from collections import Counter, defaultdict, deque
import heapq
counts = Counter("banana")
print(counts["a"], counts.most_common(1)) # 3 [('a', 3)]
groups = defaultdict(list) # missing keys start as []
for word in ["apple", "avocado", "banana"]:
groups[word[0]].append(word)
print(dict(groups)) # {'a': ['apple', 'avocado'], 'b': ['banana']}
queue = deque([1, 2])
queue.append(3) # add to the right
print(queue.popleft()) # 1 (O(1); list.pop(0) is O(n))
heap = [5, 1, 4]
heapq.heapify(heap) # min-heap
heapq.heappush(heap, 2)
print(heapq.heappop(heap), heapq.heappop(heap)) # 1 2| Need | Use | Main operations cost |
|---|---|---|
| Ordered items, index access | list | index O(1), append O(1), insert at front O(n) |
| Fast lookup by key | dict | get / set / delete O(1) on average |
| Unique items, fast "in" | set | add / in O(1) on average |
| Queue | collections.deque | append / popleft O(1) |
| Smallest item first | heapq | push / pop O(log n) |
How to say it in an interview
"Lists are mutable ordered sequences, tuples are immutable, dicts map hashable keys to values and keep insertion order, and sets give O(1) average membership. I use comprehensions instead of map and filter, sorted() when I need a new list since sort() returns None, and copy or deepcopy because assignment shares the same object. I never use a mutable default argument; I default to None and create the list inside. For interviews I reach for Counter, defaultdict, deque for queues and heapq for priority queues."
Key words
| Word | Meaning |
|---|---|
| list / tuple | Mutable / immutable ordered sequence |
| dict | Key-value mapping |
| set | Collection of unique values |
| Slicing | Taking part of a sequence with [start:stop:step] |
| Comprehension | One-line way to build a list, dict or set |
| Hashable | Can be used as a dict key or set item |
| deque / heapq | Fast double-ended queue / min-heap helpers |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.