Handbooks / Python / Chapter 1
Types and Data Structures
7 pages · ~5 min✓ Reviewed
Start here. Next up: Functions and Closures.
Python Data Model at a Glance
1. Objects and Names
intfloatboolstrbyteslisttupledictsetfrozensetNoneType- Every value is an object: id, type, value
- Names are bound to objects, not boxes
b = agives two names, one object
2. Mutable vs Immutable
| Mutable | Immutable | |
|---|---|---|
| Types | list, dict, set, bytearray | int, str, tuple, frozenset, bytes |
| Change | in place | never: rebinds |
python
a = [1] b = a b.append(2) print(a, a is b) s = t = "hi" s += "!" print(s, t)
s += rebinds s; t keeps the old object
output
[1, 2] True hi! hi
==compares value;iscompares identity- Use
isonly forNone,True,False
3. Hashable
- Hashable =
__hash__that never changes and agrees with__eq__ - Built-in immutables: hashable; built-in mutable containers: not
List and Tuple Operations and Costs
1. List = dynamic array
| Cost | Operations |
|---|---|
| O(1) | lst[i], len, append, pop() (amortized) |
| O(n) | insert(0,x), pop(0), remove(x), x in lst |
2. Methods and sorting
Dict and Set Operations and Costs
1. Hash Tables
dictandsetare hash tables- Lookup, insert, delete: O(1) average, O(n) worst case
dictkeeps insertion order since 3.7
2. Access, Iterate, Merge
| Tool | Effect |
|---|
Slicing and Comprehensions
1. Slice Rules
seq[start:stop:step], stop is exclusive- Negatives count from the end:
s[-1]is the last item - Out-of-range bounds are clamped, never raise
- A list slice copies: O(k) for k items
| Idiom | Gives |
|---|---|
Copying and Truthiness
1. Assignment vs Copies
b = acopies nothing: two names, one object- Mutating through either name shows through both
copy.deepcopy(a): recursive, slower, handles cycles
| Method | Outer | Inner |
|---|---|---|
b = a |
Built-in Types Cheat Sheet
1. Mutability and Hashing
| Type | Mutable | Hashable |
|---|---|---|
| list, dict, set | yes | no |
| tuple, str, frozenset, int | no | yes |
Check yourself
What do the two prints show?
[1]then[1, 2].- The default list is created once and shared. Use
acc=None.
def f(x, acc=[]): acc.append(x) return acc print(f(1)) print(f(2))
What does g print, and why?
[[1, 0], [1, 0]].*2repeats one inner row, so both rows are the same object. Use a comprehension.
g = [[0]*2]*2 g[0][0] = 1 print(g)