👆 Tap any section with ↗ TAP for interactive charts, worked examples & practice
CS 101 · Python — syntax, data structures, OOP, algorithms
Midterm & Final Reference · Ultra-Dense A4
Generated by AskSia.ai — graphs, formulas, traps
VARIABLES & TYPES ↗ TAP
Built-in types
TypeMutableExample
intno42, −7, 0
floatno3.14, 2e8
strno'hello'
boolnoTrue, False
NonenoNone (singleton)
listYES[1, 2, 3]
tupleno(1, 2)
dictYES{'a': 1}
setYES{1, 2, 3}
type(x) → show class isinstance(x, int) → type check
Variables = labels (not boxes)
Mutable surprise
a = [1,2]; b = a; b.append(3)a is now [1,2,3]. Both names point to same list object.
Copy semantics
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.

⚡ EXAM TRAP — IS vs ==

== 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.

STRINGS, FILES & ERRORS ↗ TAP
String formatting
name = 'Sia'; n = 42
f'{name} has {n}' → 'Sia has 42'
f'{n:.2f}' → '42.00' | f'{n:>10}' → ' 42'
MethodUse
.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 / .endswithboolean check
Files (with-open)
Read
with open('f.txt') as f:
  data = f.read()

or for line in f: for line-by-line.
Write
with open('f.txt', 'w') as f:
  f.write('hello\n')

'a' for append, 'r+' for read+write.
try / except / else / finally for error handling

Exception types: ValueError (bad value), TypeError (wrong type), KeyError (missing dict key), IndexError (list out of range), FileNotFoundError, ZeroDivisionError. Catch specifics, not bare except:.

⚡ EXAM TRAP — BARE except: HIDES BUGS

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.

CONTROL FLOW ↗ TAP
Conditionals
if cond: elif cond: else:

Truthy: nonzero numbers, non-empty strings/lists/dicts/sets, True. Falsy: 0, '', [], {}, set(), None, False.

Loops
LoopFormUse
forfor x in iter:iterate items
for i, x in enumerateget index + valueneed index
for k, v in d.items()iterate dictaccess pairs
whilewhile cond:condition-based
breakexit loopearly termination
continueskip iterskip current
Comprehensions
List
[x*x for x in range(5)] → [0,1,4,9,16]
With filter: [x for x in nums if x > 0]
Dict + set
{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 step

Iterators vs lists: range is a generator (lazy, memory-efficient). Wrap in list() to materialize. map, filter also lazy.

⚡ EXAM TRAP — MUTATING WHILE ITERATING

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.

OOP BASICS ↗ TAP
Class structure
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.

Inheritance
Subclass
class Puppy(Dog): inherits methods + attributes. Override by redefining. super().__init__(name) calls parent's init.
Method resolution order
Multiple inheritance: Python uses MRO (C3 linearization). D.__mro__ shows lookup order.
Special methods (dunder)
MethodTriggered 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).

⚡ EXAM TRAP — INSTANCE vs CLASS ATTRIBUTES

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.

ALGORITHMS — SORT & SEARCH ↗ TAP
Sorting comparison
AlgorithmBestAvgWorstStable?
BubbleO(n)O(n²)O(n²)yes
InsertionO(n)O(n²)O(n²)yes
MergeO(n log n)O(n log n)O(n log n)yes
QuickO(n log n)O(n log n)O(n²)no
HeapO(n log n)O(n log n)O(n log n)no
Python sorted()Timsort: O(n log n) avg/worstyes
Searching
Linear: O(n)
Scan one by one. Works on unsorted. Always check the whole list worst case.
Binary: O(log n)
Requires sorted input. Halve the search space each step. bisect module in Python.
Big-O: drop constants and lower-order terms. O(2n+5) → O(n). O(n² + n) → O(n²).
Recursion + DP intro

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).

⚡ EXAM TRAP — QUICKSORT WORST CASE

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.

DATA STRUCTURES ↗ TAP
Big four — pick the right one
StructureOrderUniqueMutableLookup
listyes (insertion)noyesO(n)
tupleyesnonoO(n)
dictyes (3.7+)keys yesyesO(1) avg
setnoyesyesO(1) avg
Common operations
List ops
.append(x) end. .insert(i, x) at i. .pop() end. .pop(0) front (O(n)!). For queue: collections.deque.
Dict ops
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] reverses

Tuple 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.

⚡ EXAM TRAP — LIST AS DICT KEY FAILS

Dict keys must be hashable = immutable. Tuples ✓. Strings ✓. Lists ❌ (TypeError: unhashable). Same restriction for set elements. Always tuples for composite keys: {(1,2): 'value'}.

FUNCTIONS & SCOPE ↗ TAP
Function basics
def f(x, y=10, *args, **kwargs): return x + y + sum(args) + len(kwargs)
Param typeFormUse
Positionalxrequired, in order
Defaulty=10optional
*argsvariable positionaltuple of extras
**kwargsvariable keyworddict of named extras
Keyword-onlydef f(*, k):must use k=...
Scope (LEGB)
L → E → G → B
Local (function) → Enclosing (outer function) → Global (module) → Builtin (Python).
nonlocal + global
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 only

Closures: 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.

⚡ EXAM TRAP — LATE BINDING IN LOOPS

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.

DECISION BOX — WHICH STRUCTURE / TECHNIQUE? ↗ TAP
Match the problem to the tool
Need…Use § fromBest 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)
Pythonic style
Comprehensions over manual loops. enumerate over range(len()). f-strings over %. Use built-ins (sum, max, sorted) not manual loops.
Debug checklist
Print types. Check off-by-one. Trace through with small input. Verify mutable default args don't cross calls. print(x, type(x)) first.
⚡ EXAM TRAP — INDENTATION IS SYNTAX

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.

⚡ FINAL EXAM TRAP — UNDEFINED → CRASH

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.

CS 101 · Comprehensive Cram Sheet · Ultra-Dense A4
✦ AskSia.ai
For exam prep only · Check your professor's formula sheet rules · asksia.ai/library

Want one for YOUR exact syllabus?

Sia is your free desktop study agent. Drop your professor's slides — Sia builds you a sheet tailored to YOUR test. Better than this library because it knows YOUR materials.

↓ Download Sia · Free