Overview
Miscellaneous is Section 5 of the PCAP-31-03 syllabus, which subtitles it with list comprehensions, lambdas, closures and I/O. It has five objectives. Building complex lists covers comprehensions with if conditions and nested comprehensions. Embedding lambda functions covers defining lambdas, passing them to your own functions, and using them with map() and filter(). Defining and using closures covers what a closure is and why it is useful. Understanding basic input/output terminology covers I/O modes, the predefined streams, handles versus streams, and text versus binary modes. Performing input/output operations covers open(), errno values, the close(), read(), write(), readline() and readlines() methods, and bytearray as a buffer.
The first three objectives reward fluent reading of compact functional code. The last two are about files, where most questions concern which mode to use, what a method returns and which errno value describes a failure.
How it's tested
Expect dense one-liners in this section: a comprehension with a condition, a map() over a filter(), or a function that returns a lambda. You predict the printed value. I/O items describe a file task and ask for the right mode or method, or show an exception handler testing errno and ask which message prints.
-
Evaluate a comprehension
A list comprehension with conditions or nested loops runs, and you choose the exact resulting list.
-
Trace a returned function
A function builds and returns a lambda or inner function, and you predict its output when called later.
-
Choose mode or method
A file task is described, and you select the open() mode, method or errno constant that fits it.
A snippet runs print(map(lambda x: x * 2, [1, 2])). Many candidates choose [2, 4], but in Python 3 map() returns a lazy map object, so print shows something like <map object at 0x...>. Only wrapping the call in list() produces [2, 4]. When an option shows an object description, check whether the code converts the iterator before printing.
Objectives 5
Official objectives from the OpenEDG Python Institute outline, in outline order.
5.1 Build complex lists using list comprehensionsComprehensions with if conditions and nested comprehensions.
- What it means
- This objective covers creating lists in a single expression, filtering elements with if and building lists of lists or flattened lists with nested loops.
- What to understand
- [expr for x in seq if cond] evaluates expr only for elements where cond is true. A conditional expression placed before for, as in [a if c else b for x in seq], transforms every element instead of filtering. In [x * y for x in A for y in B] the loops nest in the written order, outer first. A comprehension inside another, such as [[0 for c in range(3)] for r in range(2)], builds a two-dimensional list with independent rows.
- How it shows up
- Expect a comprehension with range(), a modulo condition or two for clauses, and an output-prediction question.
- Common confusion
- Confusing a trailing if filter with an if-else expression, which keeps every element and only changes its value.
5.2 Embed lambda functions into codeDefining lambdas, functions taking lambdas as arguments, map() and filter().
- What it means
- This objective covers anonymous single-expression functions and the common places they appear: arguments to your own functions and to the built-ins map() and filter().
- What to understand
- lambda params: expression creates a function object whose body is one expression that is returned automatically. A lambda can be stored in a variable or passed directly. map(func, iterable) applies func to every element, and filter(func, iterable) keeps elements for which func returns a truthy value. Both return lazy iterators in Python 3, so wrap them in list() to see values, and remember an iterator can be consumed only once.
- How it shows up
- Items pass lambdas to map(), filter() or a user-defined function and ask for the resulting list.
- Common confusion
- Expecting filter() to transform values; it only keeps or drops elements, while map() changes them.
5.3 Define and use closuresMeaning and rationale of closures; defining and using them.
- What it means
- This objective covers inner functions that remember variables from the enclosing function after that function has returned, and why this is useful for building configurable functions.
- What to understand
- When an outer function defines an inner function that uses one of the outer function's variables and returns it, the returned function keeps access to that variable. Calling make_multiplier(3) can return a function that multiplies by 3 every time. Each call to the outer function creates a separate environment, so two closures do not share state. The inner function can read the captured variable; changing it requires the nonlocal keyword.
- How it shows up
- Expect a function returning an inner function, called later with arguments, and a question about the printed result.
- Common confusion
- Thinking the captured variable disappears when the outer function returns; the closure keeps it alive.
5.4 Understand basic input/output terminologyI/O modes, predefined streams, handles vs. streams, text vs. binary modes.
- What it means
- This objective covers the concepts behind file processing: what a stream and a handle are, which streams exist without opening anything, and how modes change what you can do.
- What to understand
- A stream is an abstract channel for data, and a handle is the object open() returns to operate on it. Python provides three predefined streams in the sys module: sys.stdin, sys.stdout and sys.stderr. Mode letters combine: r reads, w writes and truncates, a appends, x creates and fails if the file exists, and + adds the other direction. Text mode, the default, decodes bytes to strings and translates line endings; binary mode with b works with raw bytes.
- How it shows up
- Items describe a requirement such as appending without erasing, and ask which open() mode string to use.
- Common confusion
- Assuming 'w' adds to existing content; it truncates the file the moment it is opened.
5.5 Perform input/output operationsopen(), errno values, close(), read(), write(), readline(), readlines() and bytearray buffers.
- What it means
- This objective covers opening, reading, writing and closing files, diagnosing failures through errno, and using a mutable byte buffer for binary input.
- What to understand
- open(name, mode) returns a stream object or raises an OSError subclass, such as FileNotFoundError, whose errno attribute matches constants in the errno module like ENOENT, EACCES, EEXIST, EISDIR and ENOSPC. read() returns the whole remaining content or a given number of characters, readline() returns one line including its newline, and readlines() returns a list of lines. write() returns the number of characters written. A bytearray can be filled by readinto() in binary mode.
- How it shows up
- Expect a handler comparing e.errno to errno constants, or a question about what readline() returns at end of file.
- Common confusion
- Expecting readline() to strip the newline or to raise an error at end of file; it returns an empty string.
High-yield concepts
The terms, rules and formulas this domain turns into questions most often.
-
Filtering comprehension
A trailing if keeps only elements that meet the condition.
- Remember
- Filtered elements are dropped entirely.
- Tested as
- Output prediction items.
- Trap
- Mixing it up with if-else transformation.
-
Nested comprehension
Multiple for clauses or a comprehension inside another.
- Remember
- Loops nest left to right, outer first.
- Tested as
- Two-dimensional list items.
- Trap
- Reversing the loop order.
-
lambda
An anonymous function containing a single expression.
- Remember
- The expression value is returned automatically.
- Tested as
- Function-argument items.
- Trap
- Writing return or statements inside it.
-
map()
Applies a function to every element of an iterable.
- Remember
- Returns a lazy iterator in Python 3.
- Tested as
- Output items with list().
- Trap
- Expecting a list without conversion.
-
filter()
Keeps elements for which the function returns a truthy value.
- Remember
- Also returns an iterator.
- Tested as
- Output items.
- Trap
- Expecting it to change element values.
-
Closure
An inner function that remembers variables of its enclosing function.
- Remember
- Each outer call creates a separate captured environment.
- Tested as
- Function factory items.
- Trap
- Thinking the variable is lost after return.
-
nonlocal
Lets an inner function rebind a variable from the enclosing function.
- Remember
- Without it, assignment creates a local variable.
- Tested as
- Closure state items.
- Trap
- Using global instead.
-
Predefined streams
sys.stdin, sys.stdout and sys.stderr.
- Remember
- They are open before your program starts.
- Tested as
- Terminology items.
- Trap
- Opening them with open().
-
Mode 'w' vs. 'a'
w truncates or creates; a appends or creates.
- Remember
- Opening with w erases content immediately.
- Tested as
- Mode selection items.
- Trap
- Using w to add lines.
-
Mode 'x'
Creates a new file and fails if it already exists.
- Remember
- Raises FileExistsError, errno EEXIST.
- Tested as
- Mode selection items.
- Trap
- Confusing it with w.
-
Text vs. binary mode
Text decodes to str; binary returns bytes.
- Remember
- Add b to the mode for binary.
- Tested as
- Mode and type items.
- Trap
- Writing a str to a binary stream.
-
readlines()
Returns a list of all remaining lines.
- Remember
- Each line keeps its newline character.
- Tested as
- Output format items.
- Trap
- Expecting stripped lines.
-
errno
Module of error codes compared with an exception's errno attribute.
- Remember
- ENOENT means no such file or directory.
- Tested as
- Handler output items.
- Trap
- Comparing the exception object itself to a constant.
-
bytearray
A mutable sequence of bytes usable as an I/O buffer.
- Remember
- readinto() fills it in binary mode.
- Tested as
- Binary I/O items.
- Trap
- Using an immutable bytes object as the buffer.
Side by side
Concepts candidates mix up, compared on the point that decides the answer.
map() vs. filter() vs. comprehension
| Concept | Meaning | Key difference | Common trap |
|---|---|---|---|
| map(f, seq) | Applies f to every element | Same count, changed values, iterator | Expecting a list |
| filter(f, seq) | Keeps elements where f is truthy | Fewer or equal elements, unchanged values | Expecting transformed values |
| [f(x) for x in seq if c] | Transforms and filters in one expression | Returns a list directly | Misplacing the condition |
open() modes
| Concept | Meaning | Key difference | Common trap |
|---|---|---|---|
| 'r' | Read; file must exist | Default mode | Expecting it to create a file |
| 'w' | Write; truncates or creates | Erases existing content | Using it to add lines |
| 'a' | Append; creates if missing | Writes go to the end | Expecting truncation |
| 'x' | Exclusive create | Fails if the file exists | Confusing it with w |
| 'rb' / 'wb' | Binary read or write | Works with bytes | Passing str objects |
Reading methods
| Concept | Meaning | Key difference | Common trap |
|---|---|---|---|
| read() | Remaining content as one string | Optional size argument | Expecting a list |
| readline() | One line including the newline | Returns '' at end of file | Expecting an exception at end |
| readlines() | List of remaining lines | Newlines kept in each item | Expecting stripped strings |
Exam traps
Each trap is an answer that looks right. Learn the clue that should change your mind.
-
map returns a list
- What candidates pick
- Choose [2, 4] for print(map(lambda x: x * 2, [1, 2])).
- Why it looks right
- Python 2 behaved this way.
- Why it's wrong
- Python 3 map() returns an iterator, so print shows a map object description.
Clue to watch for The call is printed without list().
-
Filter transforms
- What candidates pick
- Choose doubled values for filter(lambda x: x * 2, data).
- Why it looks right
- The lambda body doubles numbers.
- Why it's wrong
- filter() keeps elements whose result is truthy and returns the originals unchanged.
Clue to watch for A lambda inside filter() computes a value rather than a condition.
-
Closure forgets
- What candidates pick
- Expect NameError when calling a function returned from its factory.
- Why it looks right
- The outer function's local scope has ended.
- Why it's wrong
- A closure retains the enclosing variables it references, so the call works.
Clue to watch for An outer function returns an inner function that uses its parameter.
-
Append with w
- What candidates pick
- Choose 'w' to add a log line to an existing file.
- Why it looks right
- Writing sounds like the right operation.
- Why it's wrong
- 'w' truncates the file at open, erasing earlier lines; 'a' appends.
Clue to watch for The requirement says to keep existing content.
-
Stripped lines
- What candidates pick
- Expect readlines() to return ['a', 'b'] for a two-line file.
- Why it looks right
- Lines look clean when displayed.
- Why it's wrong
- Each element keeps its trailing newline, as in ['a\n', 'b\n'].
Clue to watch for The output is shown as a list.
-
Comparing the exception
- What candidates pick
- Pick a branch comparing e == errno.ENOENT.
- Why it looks right
- The exception describes the error.
- Why it's wrong
- The integer code is stored in e.errno; the exception object itself is not that integer.
Clue to watch for Handler conditions differ in whether they use e or e.errno.
Answer framework
For a Section 5 snippet or file task, work through these steps to find the answer PCAP-31-03 expects.
- Decide whether the code is a comprehension, a lambda with map() or filter(), a closure, or a file operation.
- For comprehensions, list the loop variables in order, apply the filter condition, then compute the expression for each surviving element.
- For lambdas and closures, record the captured variables and arguments, then check whether map() or filter() results are converted before printing.
- For file tasks, choose the mode from the requirement: read, truncate and write, append, exclusive create, and text or binary.
- For reading and errors, state each method's return type and end-of-file behavior, and compare e.errno against errno constants in handlers.
Practice question
Want more like this? The PCAP practice test has questions for every domain.
Checklist
0 of 14
Tick each one you can do without notes. Your ticks stay in this browser.
Study strategy
Split your preparation into two halves. For the functional half, write twenty comprehensions of growing difficulty, starting with a single loop and filter, then if-else expressions, then two for clauses, then nested lists. Predict each result before running it. Rewrite a few as explicit loops to confirm the order of nesting.
Next, practice lambdas with map() and filter(), printing the raw result once to see the iterator and then wrapping it in list(). Build a closure factory such as make_power(n), create two closures from it, and check that they keep separate values. Add a counter closure that uses nonlocal.
For the I/O half, create a small text file and open it in every mode from the syllabus: r, w, a, x, r+ and their binary forms. Observe which modes erase content, which create files and which fail. Read the file with read(), readline() in a loop and readlines(), and compare the outputs. Then trigger errors deliberately, such as a missing file, a directory name and an existing file with x, and print e.errno beside the matching errno constant. Finish by reading a binary file into a bytearray with readinto().
FAQ
How much of PCAP is Section 5, Miscellaneous?
Miscellaneous, covering comprehensions, lambdas, closures and I/O, is 22% of PCAP-31-03, and the official syllabus assigns it 9 of the 40 exam items.
Why does print(map(...)) not show a list?
In Python 3, map() and filter() return lazy iterators. Pass the result to list() or loop over it to see the values.
What is a closure in simple terms?
A function defined inside another function that remembers the outer function's variables even after the outer function has finished.
Which errno values should I recognize?
Know the common ones: ENOENT for a missing file, EACCES for permission denied, EEXIST for an existing file, EISDIR for a directory, EMFILE for too many open files and ENOSPC for no space left.
What is the difference between 'w' and 'a' modes?
Both create a missing file. 'w' truncates existing content as soon as the file opens, while 'a' keeps it and writes at the end.
What does readline() return at the end of a file?
An empty string. Lines before that include their newline character, so an empty line in the middle is returned as a newline character, not as an empty string.
Why use a bytearray for input?
A bytearray is mutable, so a binary stream's readinto() method can fill it in place, which avoids creating a new bytes object for every read.
Test your Domain 5 knowledge
You have covered comprehensions, lambdas with map() and filter(), closures, file modes and I/O methods. Test whether you can read these compact snippets correctly in timed practice.