1.1Lexical Tokens
A Token is the smallest lexical unit the Python compiler recognises. Five categories:
| Token Class | Definition | Examples |
|---|---|---|
| Keywords | Reserved; cannot be used as identifiers | if, else, for, while, def, return, global, pass, break, continue, import, from, in, not, and, or, True, False, None… |
| Identifiers | User-defined names for variables, functions, classes | Must start with letter or _; case-sensitive; no special chars |
| Literals | Fixed data values embedded in source | 42, 3.14, 'hello', True, None |
| Operators | Symbols that perform operations | +, -, *, /, //, %, **, ==, !=, <, >, and, or, not, in, is |
| Punctuators | Structural delimiters | ( ) [ ] { } , : . ; |
Exam Trap — Identifiers
- Identifiers are case-sensitive:
Data≠data. - Cannot begin with a digit; no
$,@, or other special chars. 1var→ SyntaxError;_var1→ valid.
1.2Data Types, Mutability & Memory Reference2–3 marks
In Python, variables are reference pointers to heap-allocated objects. id(x) returns the unique memory address of object x.
| Data Type | Mutability | In-place Modification | id() after reassignment |
|---|---|---|---|
| int, float, complex | Immutable | ✗ Prohibited | Changes — new object created |
| str | Immutable | ✗ TypeError on item assignment | Changes — new string buffer |
| tuple | Immutable | ✗ Prohibited | Changes — new tuple object |
| list | Mutable | ✓ append, pop, slice assign… | Same — buffer mutated in place |
| dict | Mutable | ✓ key-value insert/update/pop | Same — hash-map mutated |
| set | Mutable | ✓ add, discard, remove | Same — hash-bucket mutated |
Exam Trap — id() Questions
- For immutable types:
x = x + 1→id(x)changes (new object). - For mutable types:
lst.append(4)→id(lst)stays same (in-place). ischecks identity (sameid());==checks equality (same value).
# Immutable rebinding x = 100 print(id(x)) x += 1 # New PyObject allocated; id(x) differs print(id(x)) # Mutable in-place nums = [1, 2, 3] print(id(nums)) nums.append(4) # Same buffer; id(nums) identical print(id(nums))
1.3Operators & Operator Precedence1–2 marks
| Operator Group | Symbols | Note |
|---|---|---|
| Arithmetic | + − * / // % ** | // → floor division; ** → exponentiation |
| Relational | == != < > <= >= | Returns bool |
| Logical | and or not | Short-circuit evaluation |
| Membership | in not in | Works on str, list, tuple, dict (checks keys), set |
| Identity | is is not | Compares memory address, not value |
| Assignment | = += -= *= /= //= %= **= | Augmented assignment operators |
Precedence Order (High → Low)
** → +x −x (unary) → * / // % → + − → Relational → not → and → or1.4Conditional & Iterative Statements2–3 marks
- if / elif / else — standard conditional branching.
- for — iterates over any iterable (list, str, range, tuple…).
- while — repeats while condition is
True. - break — terminates the innermost loop immediately.
- continue — skips remaining body; proceeds to next iteration.
- pass — null statement; placeholder for empty block.
- range(start, stop, step) — generates integers from
startup to but not includingstop.
Exam Trap — Loop-else Clause (frequently tested)
A for or while may have an else suite.
- The
elseblock executes only when the loop completes normally (exhausts all iterations OR condition becomes False) without hitting abreak. - If
breakis executed →elseis skipped entirely.
for i in range(1, 4):
if i == 5: break
else:
print("Executes — no break hit") # OUTPUT: Executes — no break hit
for i in range(1, 4):
if i == 2: break
else:
print("Skipped — break was hit") # NOT printed1.5String Operations & Slicing2–3 marks
Strings are immutable sequences. Positive index: 0 → n−1 (left-to-right). Negative index: −1 → −n (right-to-left).
Syntax: s[start : stop : step] — stop is excluded; step default = 1.
| Expression | Result (s = 'PYTHON') | Explanation |
|---|---|---|
| s[0] | 'P' | First character |
| s[-1] | 'N' | Last character |
| s[1:4] | 'YTH' | Index 1, 2, 3 (4 excluded) |
| s[::-1] | 'NOHTYP' | Reversed copy |
| s[::2] | 'PTO' | Every alternate character |
Prescribed String Functions (exam-tested)
| Function | Description |
|---|---|
| s.upper() / s.lower() | Convert case |
| s.title() | Title-case (first letter of each word capitalised) |
| s.strip() / s.lstrip() / s.rstrip() | Remove whitespace (or specified chars) |
| s.replace(old, new) | Replace all occurrences of old with new |
| s.find(sub) | Return first index of sub; −1 if not found |
| s.count(sub) | Count non-overlapping occurrences |
| s.split(sep) | Split into list by separator |
| s.isdigit() / s.isalpha() / s.isalnum() | Character-class predicates → bool |
| len(s) | Number of characters |
1.6Lists2–3 marks
Lists are ordered, mutable sequences enclosed in [ ]. Support heterogeneous elements.
| Method / Operation | Effect |
|---|---|
| lst.append(x) | Appends x at end |
| lst.insert(i, x) | Inserts x at index i |
| lst.pop() / lst.pop(i) | Removes & returns last element (or element at i) |
| lst.remove(x) | Removes first occurrence of x; ValueError if absent |
| lst.sort() | Sorts in-place (ascending by default) |
| lst.reverse() | Reverses in-place |
| lst.index(x) | Returns index of first occurrence of x |
| lst.count(x) | Returns count of x in list |
| len(lst) | Number of elements |
| lst + lst2 | Concatenation — returns new list |
| lst * n | Repetition — returns new list |
Exam Trap — List Operations
remove(x)deletes by value;pop(i)deletes by index.sort()is in-place (returns None);sorted(lst)returns a new sorted list.- Slicing a list always returns a new list — original is unmodified.
1.7Tuples
- Ordered, immutable sequences enclosed in
( ). Heterogeneous allowed. - Indexing and slicing syntax identical to lists.
- Only two methods:
t.count(x),t.index(x). - Single-element tuple:
(42,)— the trailing comma is mandatory. - Tuples are faster than lists and used as dictionary keys (lists cannot be).
1.8Dictionaries2–3 marks
Unordered (insertion-ordered from Python 3.7+) mutable key–value mappings. Keys must be immutable (str, int, tuple); values may be any type.
| Method / Operation | Effect |
|---|---|
| d[key] | Access value; KeyError if absent |
| d.get(key, default) | Access value; returns default (None) if absent — no KeyError |
| d.keys() | View of all keys |
| d.values() | View of all values |
| d.items() | View of all (key, value) pairs |
| d.update(d2) | Merges d2 into d |
| d.pop(key) | Removes key and returns its value |
| del d[key] | Removes entry by key |
| len(d) | Number of key-value pairs |
| key in d | Membership test on keys |