Files
Worked examples with output, errors and complexity
Computer Science | Undergraduate (Level 4) | December 2026
WHAT IS INSIDE
1. Core Concepts and Theoretical Frameworks
2. Core data structures and their costs
3. Functions, arguments and comprehensions
4. Files, exceptions and modules
5. Objects, testing and debugging
6. Step-by-Step Worked Examples
7. Comparative Summary Table
8. Common Exam Pitfalls and Answer Technique
9. Practice Exam Questions with Model Answers
10. Glossary of Exam-Ready Definitions
1. Core Concepts and Theoretical Frameworks
Python is learned by predicting what a program will do, then running it and explaining the difference. The table
gives the eight ideas that most exercises test; the worked examples are small enough to trace by hand, and each one
ends with its output and the reason.
Concept Anchor Rule Why it matters
Immutable versus mutable int, str, tuple versus Mutable objects can change in place Aliasing bugs
list, dict, set and are shared by reference
List operations Index and slice O(1) index, O(n) insert at front, O(1) Choosing the structure
append amortised
Dictionary Hash table O(1) average lookup; keys must be Frequency counts and caches
hashable
Set Hash table of unique O(1) average membership; no order Deduplication and membership
items
Function arguments Positional, keyword, Defaults are evaluated once at definition The mutable default trap
default, star
Scope LEGB rule Local, enclosing, global, built-in Name resolution and closures
Exceptions try, except, else, Catch the narrowest exception that you Robust input and files
finally can handle
Complexity Big O Nested loops multiply; halving is Performance reasoning
logarithmic
The examinable habit is to know the cost and the identity of every operation. Cost tells you whether a loop over a
list inside a loop is acceptable; identity tells you whether two names refer to the same object, which is the source of
most surprising mutation and most marks lost on 'what is printed' questions.
2. Core data structures and their costs
A list is a dynamic array: indexing and appending are fast, insertion at the front is linear because every later
element shifts. A tuple is an immutable sequence, usable as a dictionary key and cheaper to create. A dictionary is a
hash table mapping hashable keys to values with average constant-time lookup, insertion and deletion. A set stores
unique hashable items with the same average cost for membership.
Python Programming: Data Structures, Functions and Files Page 1 of 5
,Python Programming: Data Structures, Functions and Files
Choosing the structure is a complexity decision. Searching a list for a value is linear; storing the values in a set first
turns repeated membership tests into constant time at the cost of memory. A frequency count is a dictionary with
get or a Counter; deduplication keeping order uses a dictionary or dict.fromkeys. Linked behaviour, stacks and
queues are built from lists or deque, and the choice shows up in the complexity of the whole program.
• list - ordered, mutable, O(1) index and append.
• tuple - ordered, immutable, hashable if its items are.
• dict - key-value, O(1) average lookup, insertion ordered.
• set - unique items, O(1) average membership.
3. Functions, arguments and comprehensions
Arguments are bound to parameter names at call time. Positional arguments are matched by order, keyword
arguments by name, and *args and **kwargs collect the remainder. Default values are evaluated once when the
function is defined, so a mutable default such as an empty list is shared across calls; the correct pattern is a default
of None and a fresh object inside the function.
A comprehension builds a collection in one expression and is usually faster and clearer than an equivalent loop with
append. A list comprehension evaluates eagerly and stores every item; a generator expression yields items lazily
and uses constant memory. Scope follows the LEGB rule, and a function that assigns to a name creates a local
variable unless it declares global or nonlocal, which is why reading a global works and assigning to it raises
UnboundLocalError.
4. Files, exceptions and modules
Files should be opened with a with statement so that the handle is closed even if an exception is raised. Text mode
decodes using the platform default unless an explicit encoding is given, so specifying encoding equals utf-8 is a
portability requirement rather than a style preference. Iterating over a file object yields lines, which is
memory-efficient for large files.
Exceptions are for exceptional conditions, not for ordinary control flow. A try block should contain the smallest
amount of code that can fail, the except clause should name the narrowest exception it can handle, and finally runs
whether or not an error occurred. Raising a ValueError with a clear message is better than returning a sentinel such
as None, because the caller cannot silently ignore a missing result.
5. Objects, testing and debugging
A class bundles state and behaviour. The constructor initialises attributes, methods receive the instance as their first
parameter, and a class attribute is shared while an instance attribute is per object. Special methods such as
__repr__, __eq__ and __len__ integrate the object with built-in functions and with print, which is why they are the
first methods to implement in an exam answer.
Testing is part of the answer, not an afterthought. A unit test asserts a specific expected value for a specific input,
and a good test fails when the code is wrong rather than when the code is merely different. Reading a traceback
from the bottom up identifies the error type and line first, then the call chain; printing intermediate values or using
assert statements localises the fault faster than rereading the whole program.
6. Step-by-Step Worked Examples
Four programs, each traced by hand before the output is given. The code is deliberately short so every step can be
followed.
Example 1: counting words with a dictionary
Task. Count how often each word appears in a sentence, ignoring case and punctuation, and return the three most
common.
text = 'the cat and the dog and the bird'
counts = {}
Python Programming: Data Structures, Functions and Files Page 2 of 5