Generated by AskSia.ai — graphs, formulas, traps
| Type | Mutable | Example |
|---|---|---|
| int | no | 42, −7, 0 |
| float | no | 3.14, 2e8 |
| str | no | 'hello' |
| bool | no | True, False |
| None | no | None (singleton) |
| list | YES | [1, 2, 3] |
| tuple | no | (1, 2) |
| dict | YES | {'a': 1} |
| set | YES | {1, 2, 3} |
type(x) → show class isinstance(x, int) → type checka = [1,2]; b = a; b.append(3) → a is now [1,2,3]. Both names point to same list object.b = a.copy() for shallow copy. copy.deepcopy(a) for nested. Tuples + ints + strs are immutable so no copy needed.String methods: .upper() .lower() .split() .strip() .replace() f'{x}'Type coercion: int('42') = 42, str(42) = '42', float('3.14') = 3.14. '1' + 1 → TypeError — Python doesn't auto-convert.
== compares values; is compares identity (same object in memory). [1,2] == [1,2] is True; [1,2] is [1,2] is False (different list objects). Use is only for None: x is None.
name = 'Sia'; n = 42
f'{name} has {n}' → 'Sia has 42'
f'{n:.2f}' → '42.00' | f'{n:>10}' → ' 42'| Method | Use |
|---|---|
| .split(sep) | break string into list |
| .join(iter) | '-'.join(['a','b']) → 'a-b' |
| .strip() | remove whitespace |
| .replace(a, b) | swap substrings |
| .find(sub) | index or −1 if not found |
| .startswith / .endswith | boolean check |
with open('f.txt') as f:
data = f.read()or
for line in f: for line-by-line.with open('f.txt', 'w') as f:
f.write('hello\n')'a' for append, 'r+' for read+write.
try / except / else / finally for error handlingException types: ValueError (bad value), TypeError (wrong type), KeyError (missing dict key), IndexError (list out of range), FileNotFoundError, ZeroDivisionError. Catch specifics, not bare except:.
except: alone catches everything including KeyboardInterrupt and SystemExit. Bugs hide. Always specify the exception type: except ValueError:. Use except Exception: if you must catch broadly but want to log.
if cond: elif cond: else:Truthy: nonzero numbers, non-empty strings/lists/dicts/sets, True. Falsy: 0, '', [], {}, set(), None, False.
| Loop | Form | Use |
|---|---|---|
| for | for x in iter: | iterate items |
| for i, x in enumerate | get index + value | need index |
| for k, v in d.items() | iterate dict | access pairs |
| while | while cond: | condition-based |
| break | exit loop | early termination |
| continue | skip iter | skip current |
[x*x for x in range(5)] → [0,1,4,9,16]With filter:
[x for x in nums if x > 0]{k: v*2 for k, v in d.items()}{x for x in lst if x > 0} (set, deduplicates)range(start, stop, step) → start ≤ i < stop in steps of stepIterators vs lists: range is a generator (lazy, memory-efficient). Wrap in list() to materialize. map, filter also lazy.
Modifying a list while iterating it leads to weird bugs. for x in lst: lst.append(...) can loop forever or skip items. Iterate over a copy: for x in lst[:]: or build a new list.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f'{self.name}!'__init__ is the constructor. self is the instance reference (like this in other languages). Always first parameter of instance methods.
class Puppy(Dog): inherits methods + attributes. Override by redefining. super().__init__(name) calls parent's init.D.__mro__ shows lookup order.| Method | Triggered by |
|---|---|
| __init__ | Dog('Rex') |
| __str__ | str(d), print(d) |
| __repr__ | repr(d), in REPL |
| __eq__ | d1 == d2 |
| __len__ | len(d) |
| __getitem__ | d[0] |
Encapsulation conventions: _name = treat as private (Python won't enforce). __name = name-mangled (becomes _ClassName__name).
class Dog: tricks = [] creates a class attribute shared by all instances. If one dog does self.tricks.append(...), all dogs see it. Define mutable attributes inside __init__ as instance attrs.
| Algorithm | Best | Avg | Worst | Stable? |
|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | yes |
| Insertion | O(n) | O(n²) | O(n²) | yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | yes |
| Quick | O(n log n) | O(n log n) | O(n²) | no |
| Heap | O(n log n) | O(n log n) | O(n log n) | no |
Python sorted() | Timsort: O(n log n) avg/worst | yes | ||
bisect module in Python.Big-O: drop constants and lower-order terms. O(2n+5) → O(n). O(n² + n) → O(n²).Recursion: function calls itself with smaller input. Always have a base case + recursive case. Naive Fibonacci is O(2ⁿ) — exponential blowup. Memoize to drop to O(n).
Quicksort is O(n log n) average but O(n²) worst (when pivot is always smallest/largest — already-sorted input with naive pivot). Production implementations use random pivot or median-of-three to avoid this.
| Structure | Order | Unique | Mutable | Lookup |
|---|---|---|---|---|
| list | yes (insertion) | no | yes | O(n) |
| tuple | yes | no | no | O(n) |
| dict | yes (3.7+) | keys yes | yes | O(1) avg |
| set | no | yes | yes | O(1) avg |
.append(x) end. .insert(i, x) at i. .pop() end. .pop(0) front (O(n)!). For queue: collections.deque.d[k] get (KeyError if missing). d.get(k, default) safe. d.setdefault(k, default) get-or-add. collections.defaultdict for auto-init.Slicing: lst[start:stop:step] lst[::-1] reversesTuple unpacking: a, b = (1, 2). Swap: a, b = b, a. Star: head, *tail = [1,2,3,4] → head=1, tail=[2,3,4].
List vs tuple choice: tuple if data won't change (return values, dict keys, set elements). List if you'll modify. Tuples slightly faster + memory-efficient.
Dict keys must be hashable = immutable. Tuples ✓. Strings ✓. Lists ❌ (TypeError: unhashable). Same restriction for set elements. Always tuples for composite keys: {(1,2): 'value'}.
def f(x, y=10, *args, **kwargs): return x + y + sum(args) + len(kwargs)| Param type | Form | Use |
|---|---|---|
| Positional | x | required, in order |
| Default | y=10 | optional |
| *args | variable positional | tuple of extras |
| **kwargs | variable keyword | dict of named extras |
| Keyword-only | def f(*, k): | must use k=... |
global x writes to module scope. nonlocal x writes to enclosing (closures). Without these, assignment creates LOCAL variable.Lambda: lambda x, y: x + y anonymous, single expression onlyClosures: inner function 'remembers' enclosing scope. Used for decorators, factories. Be careful with mutable closure variables in loops (late binding).
Decorators: @decorator wraps a function. Common: @functools.lru_cache, @property, @staticmethod, @classmethod.
fns = [lambda: i for i in range(3)] — all 3 lambdas return 2 (the final i). The closure captures the name i, not its value at definition. Fix: lambda i=i: i binds default at definition time.
| Need… | Use § from | Best choice |
|---|---|---|
| fast membership check | § ③ | set or dict (O(1)) |
| preserve order, allow dup | § ③ | list |
| composite immutable key | § ③ | tuple |
| key → value mapping | § ③ | dict |
| queue (FIFO) | § ③ | collections.deque |
| frequency count | § ③ | collections.Counter |
| 'is X in big list' | § ③ | convert to set first |
| iterate index + value | § ② | for i, x in enumerate(lst) |
| filter + transform | § ② | list comprehension |
| sum of even numbers | § ② | sum(x for x in lst if x%2==0) |
| break out of nested loops | § ② | flag + break OR refactor into function with return |
| variable args | § ④ | *args, **kwargs |
| caller can choose param | § ④ | keyword arg with default |
| cache function result | § ④ | @functools.lru_cache decorator |
| OOP with shared behavior | § ⑤ | inheritance: class Sub(Base) |
| method on class itself | § ⑤ | @classmethod or @staticmethod |
| computed attribute | § ⑤ | @property |
| format number with decimals | § ⑥ | f'{x:.2f}' |
| read file line-by-line | § ⑥ | for line in f: (within with open) |
| handle missing file | § ⑥ | except FileNotFoundError |
| sort by custom key | § ⑦ | sorted(lst, key=lambda x: x.attr) |
| find in sorted list | § ⑦ | bisect (O(log n)) |
| recursive problem | § ⑦ | memoize if subproblems repeat (DP) |
enumerate over range(len()). f-strings over %. Use built-ins (sum, max, sorted) not manual loops.print(x, type(x)) first.Python's blocks are defined by indentation, not braces. Mixing tabs and spaces breaks code silently. Use 4 spaces consistently. Most exams want consistent indentation; auto-graders fail on inconsistent whitespace.
print(x) when x doesn't exist → NameError. d['missing'] → KeyError. lst[100] on short list → IndexError. Each is a different exception type. Catch the specific one to handle gracefully.