Interview bank: output prediction and debugging
A structured rehearsal with model explanations, evaluation signals and follow-up constraints. These are original representative questions, not a claimed company interview bank.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 30 minutes; optional deep dive: 20 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain reasoning before implementation
- Identify assumptions and edge cases
- Assess an answer against explicit signals
Interview rehearsal
30-minute suggested practice budget. No automatic timer or grading. Answer first, then compare the explanation and evaluation signals.
Common representative Python interview themes, not a measured frequency ranking or a claim about a particular company.
1. Predict the results after copying a two-dimensional list and appending to one nested row. Which copy strategies actually isolate the rows?
Reveal answer and evaluation signals
A shallow copy creates a new outer list but retains references to the original rows. Mutating a shared row is visible through both outer lists. Replacing a row in one outer list is different: that changes only its own reference. Copy each row or use an appropriate deep copy when nested independence is required.
How it works
List copying duplicates the sequence of references, not the referenced objects. deepcopy recursively copies supported objects and uses a memo table to handle cycles and preserve repeated references within the copied graph. Consequently, a deep copy can be independent of the original while still containing internal aliases corresponding to the original graph.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
For rectangular numeric rows, copying each row often communicates exactly the intended ownership. For arbitrary object graphs, consider immutable representations or domain-specific reconstruction before using deepcopy, which may be expensive or inappropriate for external resources.
Pitfalls and edge cases
- Constructing rows with [[0] * width] * height repeats one row reference.
- Deep copying locks, handles, and shared services is not a general isolation strategy.
- Traces both reference levels
- Distinguishes replacing and mutating rows
- Selects an ownership-aware copy
Follow-up: Does deepcopy necessarily remove all alias relationships inside a structure?
No. If two original fields reference one object, deepcopy normally makes those fields reference one corresponding copied object. To remove an intentional alias, reconstruct the fields independently and define that change as part of the data model.
Interview-ready takeaway
Draw the reference graph before predicting nested-copy behavior; independence from the source does not mean every internal alias disappears.
2. Why do callbacks created in a loop all report the final loop value, and what are two ways to capture each iteration's value?
Reveal answer and evaluation signals
Closures normally capture a variable binding, not a frozen value at creation time. Calling the callbacks after the loop reads the binding's final value. A default parameter can bind the current value when each function is created, or a factory can create a fresh enclosing binding for every callback.
How it works
A nested function can retain a closure cell for a name from its enclosing scope. Several functions made in the same loop share access to that cell. Default expressions are evaluated at each function-definition execution, so binding the current integer as a default avoids later cell lookup for that parameter.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Prefer a factory when a callback has several captured settings or a public signature that should not expose artificial default parameters. functools.partial is also useful for binding arguments to an existing function without inventing a closure.
Pitfalls and edge cases
- Calling callbacks immediately inside the loop can hide the bug.
- An early-bound mutable default is still a reference to a mutable object, not a recursive snapshot.
- Explains late binding
- Repairs using defaults or factory
- Distinguishes capturing mutable references
Follow-up: Does a default parameter snapshot the contents of a mutable object?
No. A list captured as a default can still be mutated elsewhere. Copy the relevant state or capture an immutable representation if later mutations must not affect callback behavior, and document whether live or snapshot semantics are intended.
Interview-ready takeaway
Closure cells provide live bindings. Use explicit argument binding or fresh scopes when callback behavior requires per-iteration values.
3. A generator passes an any check but later yields fewer records than expected. Where did the missing record go?
Reveal answer and evaluation signals
Iterators are consumable stateful objects. any stops after the first truthy element, but the elements it inspected have already been consumed. Iterating the same generator resumes after that point. A list is reusable through fresh iterators; an existing iterator normally returns itself from iter and cannot be restarted.
How it works
Calling next advances an iterator until it raises StopIteration. Generator execution suspends at yield and retains its local state. Functions such as any, sum, and list consume values through that same protocol. Calling iter on an iterator does not reconstruct the source or reset the suspended function.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
If multiple passes are required and input is bounded, materialize it once and account for memory. For larger sources, redesign to compute several aggregates in one pass or provide a callable that deliberately constructs a new independent source.
Pitfalls and edge cases
- Membership tests against an iterator also consume values while searching.
- A generator's truth value does not indicate whether it has remaining items; generator objects are ordinarily true.
- Traces short-circuit consumption
- Distinguishes iterable and iterator
- Offers bounded buffering or a new source
Follow-up: Would itertools.tee make two independent passes without a memory cost?
No. tee buffers values until slower consumers catch up. If one branch runs far ahead, buffering can approach the size of the source. It is not a free replay mechanism or a replacement for a bounded streaming design.
Interview-ready takeaway
Iterator consumption is observable state. Identify every consumer before assuming a later pass will see the original data.
4. Why does removing even numbers from a list while iterating it skip some values, and how should the filter be implemented?
Reveal answer and evaluation signals
List iteration advances through indices while removals shift later elements left. The iterator can therefore step past a value that moved into the current position. Build a filtered result, or assign the filtered values to the original list's full slice if existing aliases must observe the replacement contents.
How it works
A list iterator does not provide a stable snapshot of the original sequence. Structural mutation changes what its advancing cursor encounters. A comprehension over the unmodified source can first compute a safe result. Slice assignment then mutates the original list after computation, preserving that outer object's identity for aliases.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Return a new list for functional transformation APIs. Use slice replacement only when in-place mutation is part of the ownership contract. For very large data, a separate result still costs memory, so consider whether a documented iterator-based filter is more appropriate.
Pitfalls and edge cases
- Removing by value also searches for a matching element and can make a loop quadratic.
- Changing dictionary or set size during iteration commonly raises RuntimeError rather than producing a useful traversal.
- Explains index shifting
- Preserves or replaces identity intentionally
- Distinguishes dictionary mutation rules
Follow-up: Why is iterating a snapshot useful when keys must be deleted from a dictionary?
Iterate list(mapping) to capture keys before deletions, or build a replacement mapping. The snapshot contains keys rather than cloned values, so it avoids structural iteration invalidation but does not isolate concurrent mutations of nested objects.
Interview-ready takeaway
Do not mix structural mutation with assumptions about a stable traversal; choose replacement identity and memory use deliberately.
5. A function prints a module variable and then assigns to that name. Why does the print raise UnboundLocalError?
Reveal answer and evaluation signals
An assignment anywhere in a function normally makes that name local throughout the function's scope. Reading it before that local binding has a value raises UnboundLocalError, even if a global with the same spelling exists. Use explicit parameters and return values, or declare global or nonlocal when shared rebinding is intentional.
How it works
Python determines local variable bindings from the function body rather than choosing a scope dynamically at each line. nonlocal targets an existing binding in an enclosing function scope; global targets the module namespace. Attribute mutation and method calls do not assign to the base variable name, whereas augmented assignment to a name normally does.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Prefer explicit state objects or returned values for code that needs testable dependencies. Closures are useful for compact private state, but module globals can make tests and concurrency behavior difficult to reason about because unrelated callers share them.
Pitfalls and edge cases
- Adding a later assignment can unexpectedly change an earlier read's scope.
- global does not search arbitrary caller scopes; Python uses lexical rather than dynamic scoping.
- Explains compile-time local classification
- Differentiates global and nonlocal
- Distinguishes mutation from rebinding
Follow-up: Why can a nested function append to an outer list without nonlocal?
append mutates the referenced list and does not rebind the outer name. The nested function can resolve that name normally. Writing items = items + [value] would rebind it and requires nonlocal if the outer binding should change.
Interview-ready takeaway
Name-binding rules are lexical and determined for the whole function; distinguish rebinding state from mutating a referenced object.
6. Importing a module unexpectedly registers the same plugin twice. What executes on import, and how would you investigate without real external side effects?
Reveal answer and evaluation signals
Module top-level statements run when the module is first initialized. Ordinary later imports normally reuse the module in sys.modules, but reloads, different module names, or separate interpreters can execute initialization again. Keep registration explicit and idempotent rather than assuming import is a one-time application lifecycle hook.
How it works
The import system creates a module namespace and executes its code, usually caching the module by its qualified name. The cache is per interpreter and is not durable state. The example uses compile and exec in isolated dictionaries to illustrate top-level execution and name guards; it deliberately does not emulate import caching.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Define a register(registry) function with an explicit duplicate policy and call it from application startup. Test its repeated-call behavior using an in-memory registry. Inspect module names and startup paths before blaming the import cache itself.
Pitfalls and edge cases
- A main guard does not prevent unguarded top-level registration or expensive computation.
- Using exec on untrusted source would introduce code execution; this example accepts no external source.
- Explains initialization and module cache
- Identifies repeated execution paths
- Moves effects behind explicit functions
Follow-up: What does an if __name__ == '__main__' guard protect?
It protects the guarded command entry point from ordinary import. It does not stop class definitions, decorators, or other top-level expressions outside the guard from running. Keep reusable module import behavior lightweight and predictable.
Interview-ready takeaway
Import initializes code, not just declarations. Make externally meaningful startup effects explicit and safe under repeated initialization.
7. A logging decorator prints a message but every decorated call returns None. Locate the bug and preserve the original result.
Reveal answer and evaluation signals
The wrapper probably calls the original function without returning its result. A function reaching the end implicitly returns None. The decorator must return the wrapper at decoration time, and the wrapper must return the wrapped call's result at call time. These are separate return obligations.
How it works
Decorator syntax replaces the function binding with the result of applying the decorator. The replacement wrapper receives subsequent calls and controls forwarding. functools.wraps updates metadata and sets __wrapped__ for introspection, but it does not automatically forward arguments, preserve return values, or implement an exception policy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Define which observable behavior the decorator is allowed to change: logging, metrics, access checks, retries, or result conversion. For a transparent wrapper, test success values, keyword-only arguments, and exceptions rather than only testing that a log line appears.
Pitfalls and edge cases
- Returning wrapper() executes the function during decoration instead of installing a callable.
- Catching every exception and returning None turns failures into misleading successful-looking results.
- Identifies both return sites
- Preserves arguments and results
- Uses wraps for metadata
Follow-up: How should a decorator handle exceptions from the wrapped function?
Usually allow the original exception to propagate. If adding diagnostics, record safe context and re-raise with bare raise to preserve traceback information. Translate errors only when the decorator explicitly defines a documented domain boundary.
Interview-ready takeaway
A decorator replaces a callable. Preserve the callable's argument, result, exception, and metadata contracts intentionally rather than assuming wraps handles behavior.
8. A decorator around async def logs completion before the operation runs. Why, and what does a genuinely asynchronous wrapper require?
Reveal answer and evaluation signals
Calling an async function creates a coroutine object without executing its body. A synchronous wrapper that merely returns that coroutine cannot observe its completion. An async wrapper must await the wrapped coroutine inside its own control flow, then return the resulting value while preserving failures and cancellation.
How it works
async def defines a coroutine function whose call returns an awaitable object. Execution begins when the coroutine is awaited or scheduled. An asynchronous decorator can surround the await with try/finally so cleanup occurs on success, failure, or cancellation. wraps preserves metadata but does not change a synchronous wrapper into a coroutine function.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Use separate wrappers for synchronous and asynchronous APIs when their execution contracts differ. Frameworks may inspect coroutine-function status, so returning an awaitable from an ordinary function can affect integration even if a direct await works.
Pitfalls and edge cases
- Calling without awaiting can produce an unexecuted coroutine and a runtime warning.
- Catching BaseException indiscriminately can swallow cancellation and interfere with structured concurrency.
- Separates coroutine creation and execution
- Awaits inside wrapper
- Preserves cancellation and return value
Follow-up: Can a synchronous function returning a coroutine still be awaitable by its caller?
Yes, the caller can await the returned object. However, the wrapper itself is not a coroutine function, and synchronous try/finally around coroutine creation cannot observe later execution. The distinction matters for introspection, cleanup, and framework dispatch.
Interview-ready takeaway
Awaitable results and coroutine functions are related but different. Wrap the awaited execution when behavior depends on completion.
9. Predict a and b or c when a is zero. Why is this expression not a safe replacement for b if a else c?
Reveal answer and evaluation signals
and and or return operands and short-circuit based on their truth values. In a and b or c, a false a chooses c, but even a true a still chooses c if b is false. A conditional expression selects by a alone, so it correctly preserves a meaningful zero or empty b.
How it works
and evaluates its right operand only if the left is true; or evaluates its right operand only if the left is false. Comparisons usually return booleans, but boolean operators themselves preserve chosen operands. Operator precedence makes and bind more tightly than or, which does not repair the false-middle-operand problem.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Use boolean operators for conditions or deliberate operand selection, such as a documented nonempty-string fallback. Use a conditional expression when selecting between two arbitrary values. Prefer explicit branches if either path contains substantial work or an important error boundary.
Pitfalls and edge cases
- The result of x and y is not guaranteed to be bool.
- Adding a truth test may invoke user-defined __bool__ or __len__, which can have cost or raise errors.
- Predicts operand values
- Explains short-circuiting
- Uses conditional expression for branching
Follow-up: How can short-circuiting guard an unsafe operation, and what limitation remains?
A guard such as divisor != 0 and total / divisor > 2 avoids dividing when the divisor is zero. It does not validate unrelated types or prevent state changing between separate operations in concurrent code.
Interview-ready takeaway
Short-circuit operators control evaluation and return operands; conditional expressions select values without reinterpreting the selected branch's truth.
10. A return in finally replaces the value returned by try. Explain the output and how resource cleanup should be structured instead.
Reveal answer and evaluation signals
A finally suite runs while a return or exception is leaving the protected block. A new return inside finally replaces the pending return and can suppress an exception. Cleanup should normally perform necessary release work without returning, and context managers should suppress exceptions only under an explicit documented policy.
How it works
Python saves a pending control-flow outcome before executing finally. If finally completes normally, that outcome resumes. If it returns or raises, the new outcome takes precedence. A with statement invokes __exit__ after successful entry and supplies exception information when the body fails; its return value controls exception suppression.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Use context managers to localize resource lifetime and test both successful and failing bodies. Keep cleanup idempotent where possible. If cleanup itself can fail, define how the primary error and cleanup failure will be recorded or chained without silently losing either.
Pitfalls and edge cases
- A return in finally can hide even a serious failure from the body.
- Cleanup is not guaranteed after forced process termination or an interpreter crash.
- Explains pending control flow
- Avoids return in finally
- Knows context suppression semantics
Follow-up: What does a truthy __exit__ return value do?
When an exception occurred, a truthy __exit__ result tells with to suppress it. Return false or None for ordinary cleanup. Suppress only an expected, narrowly identified condition that the manager actually knows how to handle.
Interview-ready takeaway
Cleanup should preserve the original outcome unless replacement is intentional; finally and context managers are control-flow mechanisms, not just convenience syntax.
11. An input helper accepts True as an integer age and accepts '-3' without complaint. How would you define and enforce a precise boundary?
Reveal answer and evaluation signals
Validation must state accepted types and domain constraints. bool is a subclass of int, so isinstance(True, int) is true even when booleans are inappropriate ages. Decide whether text conversion is allowed, reject booleans explicitly or require exact int, and then enforce a nonnegative range.
How it works
Constructors such as int perform conversions, not domain validation. They can accept values or transformations broader than a protocol intends, including truncating floats. A validation boundary should first identify the permitted representation, then parse it with narrow handling, then enforce semantic constraints such as lower and upper bounds.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Keep wire-format parsing separate when forms or JSON permit several representations. Return field-specific errors suitable for the caller without echoing sensitive payloads. Validate once at the trust boundary and preserve typed domain values internally.
Pitfalls and edge cases
- int(3.9) silently truncates and should not implement an exact-integer schema.
- assert is a debugging aid, not a reliable validator for untrusted input.
- Recognizes bool/int relationship
- Separates parsing and validation
- Returns explicit invalid results or errors
Follow-up: Why should conversion and range checks not be hidden inside a broad exception handler?
A broad handler can catch a defect in subsequent business logic and misreport it as bad input. Restrict try to the actual conversion and catch only expected conversion exceptions, then perform explicit semantic checks.
Interview-ready takeaway
Parsing, type acceptance, and domain validation are separate policies. Test booleans, boundaries, and missing values rather than only happy paths.
12. A recursive function catches its failure and raises a clearer error, but logs lose the original cause. How should exception chaining be used?
Reveal answer and evaluation signals
Translate an exception at a genuine abstraction boundary using raise NewError(...) from original. The caller receives a domain-appropriate failure while the traceback retains an explicit causal chain. Bare raise inside a handler rethrows the current exception. Avoid constructing a replacement exception merely to hide information needed for debugging.
How it works
Python records exception context when another exception is raised during handling. Explicit chaining sets __cause__ and gives the relationship a deliberate meaning. Suppressing displayed context with from None does not make the underlying operation succeed; it changes presentation. The exception class and safe contextual fields should carry the public contract.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Translate when crossing from a library-specific failure to a stable domain API. Within one layer, rethrowing or letting the exception propagate usually keeps diagnosis simpler. Operational logs can record the chain while user-facing output remains concise and appropriately sanitized.
Pitfalls and edge cases
- raise error can alter traceback presentation compared with bare raise.
- Including complete submitted payloads in exception text can leak private or secret data.
- Uses explicit cause
- Distinguishes rethrow and translation
- Avoids exposing sensitive input
Follow-up: When is raise ... from None appropriate?
Use it when an implementation detail would confuse the intended audience and a higher-level message fully describes recovery. Preserve detailed internal diagnostics through a safe channel; do not suppress context merely to make unexplained failures look cleaner.
Interview-ready takeaway
Exception translation should improve abstraction without destroying causality. Preserve useful evidence and control what reaches public output.
13. A generator raises StopIteration internally and its consumer reports RuntimeError. What is the correct way for a generator to finish?
Reveal answer and evaluation signals
A generator should return or reach the end to finish normally. An unintended StopIteration escaping from its body is transformed into RuntimeError, preventing accidental silent truncation. Catch exhaustion from an iterator you drive manually, or use next(iterator, sentinel) when missing data is a normal case.
How it works
A generator's own completion uses StopIteration at the iterator protocol boundary, but explicit or accidental StopIteration from inside its executing body is treated differently. This prevents a failed next call buried inside processing from masquerading as valid completion. A unique sentinel can separate end-of-input from legitimate yielded values such as None.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Use ordinary for loops for simple delegation and yield from when forwarding a subgenerator is the actual intent. Manual next calls are appropriate for lookahead or structured parsing, but every exhaustion path should have an explicit meaning.
Pitfalls and edge cases
- Replacing the sentinel with None loses the distinction between exhaustion and a valid None item.
- Catching RuntimeError broadly would hide unrelated generator bugs instead of addressing the source of exhaustion.
- Explains generator exhaustion conversion
- Uses return for completion
- Handles empty underlying iterators
Follow-up: How is return value carried when yield from delegates to a generator?
A generator's return expression becomes the value attached to its completion StopIteration. yield from captures that value as its expression result. It is separate from the individual values the delegated generator yields to callers.
Interview-ready takeaway
Terminate generators with return, not an escaping StopIteration. Treat internal iterator exhaustion as a condition that requires explicit handling.
14. A dictionary view seems to change after it was saved in a variable. Is it a snapshot, and how can a stable report be produced?
Reveal answer and evaluation signals
Dictionary keys, values, and items views are live views of the mapping. Saving the view does not copy its contents. Materialize a list or tuple when a stable collection of entries is required, remembering that the referenced values are still shallowly shared and may themselves be mutable.
How it works
A view references its original dictionary and reflects later changes when iterated. A list of items stores newly created key-value pairs at the time of traversal but keeps references to the original keys and values. Dictionary iteration order follows insertion order, while deleting and reinserting a key can move its position.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
For a report, define whether stable membership is sufficient or whether values must also be frozen. Copy immutable report fields under the same synchronization or transactional boundary that protects writers. Avoid calling a shallow list conversion a complete data snapshot.
Pitfalls and edge cases
- Changing dictionary size during view iteration can raise RuntimeError.
- A snapshot of references does not protect nested mutable values from later edits.
- Recognizes live views
- Creates explicit snapshots
- Distinguishes structural and nested stability
Follow-up: Is list(mapping.items()) an atomic snapshot under arbitrary concurrent mutation?
No general cross-thread atomicity promise follows from that expression. Coordinate readers and writers with an appropriate lock or obtain a consistent immutable version. Interpreter-specific behavior is not a substitute for an application-level consistency contract.
Interview-ready takeaway
Views are live and copied entries are shallow. Stable reporting requires an explicit membership, value, and concurrency consistency policy.
15. A sorted call leaves the original list unchanged, while assigning list.sort() produces None. Explain both APIs and stable sorting.
Reveal answer and evaluation signals
sorted(iterable) builds and returns a new sorted list. list.sort() changes a list in place and returns None to discourage treating it as a new value. Both support key functions and stable sorting: elements with equal keys preserve their original relative order, including when reverse=True is requested.
How it works
A key function maps each element to a comparison key and is evaluated once per element for that sort. Tuple keys use lexicographic comparison, allowing independent criteria when their types support ordering. Stability preserves input order among equal keys, which can encode deliberate tie behavior but does not create a total order by itself.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
When to choose it and what it costs
Use sorted when input ownership is shared or any iterable should be accepted. Use sort when the caller owns the list and mutation is intended. For externally visible pagination or ranking, add a unique tie-breaker rather than depending on incidental arrival order.
Pitfalls and edge cases
- reverse=True reverses all key dimensions rather than only one criterion.
- Mixed incomparable key types can raise TypeError, so normalize data before sorting.
- Distinguishes sorted and sort
- Explains mutating method return
- Uses key and stability
Follow-up: How would you sort by descending score and then ascending name?
For numeric scores use a key such as (-score, name). Alternatively perform stable sorts from the least significant criterion to the most significant. Define handling for missing values and duplicate names if a total deterministic ordering is required.
Interview-ready takeaway
Separate allocation, mutation, and ordering contracts. Stable sorting preserves ties but deterministic interfaces often need an explicit unique tie-breaker.
Run an honest rehearsal
Output prediction is a state trace. For nested collections, track outer slots and row objects separately before you run the program.
Understand first
Two rows that print the same can be separate objects or the same object repeated. A mutation distinguishes these states.
Words you will see
- Reference graph
- A conceptual map of names and containers pointing to objects.
- Alias
- Another route to the same object.
- Row reconstruction
- Creating each row independently instead of repeating one row reference.
Trace the repeated row
The multiplication creates two references to one [0] row. Appending through grid[0] changes that row, so grid[1] also displays the new value. The printed identity check confirms one shared row.
The list comprehension builds [0] on each iteration. Its two row objects start equal but are independent. Changing one leaves the other alone. The program does not need a memory address to establish either fact.
Test a hypothesis, not a guess
Predict both row values and row identity. If you guessed only the final printed values, you might miss the ownership mechanism. Change the construction while keeping the mutation fixed to isolate the cause.
For h rows of width w, constructing independent row slots takes O(h * w) time and space. Repeating a row is cheaper in row storage but violates independence. deepcopy preserves internal alias patterns, so it is not automatically the same as reconstructing each row.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
grid = [[0]] * 2Store the same row reference twice.
grid[0].append(5)Mutate that one shared row.
print(grid[0] is grid[1])Observe the shared identity without printing an address.
separate = [[0] for _ in range(2)]Build one new row per iteration.
Answer without the model response first. State your assumptions, give a small example and discuss an edge case. The suggested time is a practice budget, not an automatic timer, proctoring claim or hiring-readiness prediction.
Conceptual alias graph, not a measured heap trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Outer slotsgrid[0] and grid[1] each hold a reference.
- Shared rowBoth references target one [0] object.
- MutationAppending changes that one row, visible through both slots.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change the row count.
Try: Use grid = [[0]] * 3.
All three displayed rows include five because they share one row.
Replace instead of mutate.
Try: Use grid[0] = [5] instead of append.
Only the first outer slot changes; the other still points to [0].
Before you move on
If three grid slots share one row, how many row objects does an append through the third slot mutate?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
One row object. All three slots display the change because they point to it; three displayed changes do not mean three mutation operations.
Use the rubric, not keyword matching
A callback can read a variable later rather than freezing its current value. Predict when the name is read, not only when the function is created.
Understand first
A loop can create several callbacks that all report the final loop value. Test them after the loop to reveal the binding rule.
Words you will see
- Closure
- A function retaining access to an enclosing binding.
- Late binding
- Reading a retained binding when the function is called.
- Early binding
- Storing the current argument reference when a function is created.
Separate creation from invocation
Each late lambda reads the same loop variable after construction finishes. That variable is two. Each early lambda has a default evaluated during its own definition, so its parameter retains zero, one or two.
Calling callbacks inside the loop can hide the bug: the current value happens to be the desired value then. Delayed invocation is the changed case that tests the actual requirement.
Specify what is captured
A default captures a reference, not a deep snapshot. Capturing a list means later list mutations remain visible. Use an immutable value, an explicit copy, a factory or partial according to the ownership contract.
Creating n small callbacks takes O(n) objects and storage. Invocation cost includes the callback body. The early-default solution changes the visible signature; a factory can hide that implementation parameter when signature stability matters.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
late = []Prepare storage for delayed calls.
late.append(lambda: number)Keep a callable that reads the loop binding later.
early.append(lambda number=number: number)Evaluate a separate default for this definition.
print([call() for call in early])Invoke after construction to reveal the captured defaults.
An answer can be correct without matching the model wording. Evaluate whether the reasoning establishes the contract and handles follow-ups. A self-rating or revealed answer must not become an independently judged coding pass.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reduce the loop.
Try: Change range(3) to range(2).
Late calls both return one; early calls return zero and one.
Rebind after construction.
Try: Insert number = 9 before the prints.
Late calls now return nine; early defaults stay zero, one and two.
Before you move on
If the loop is range(4), what do the two callback lists return after it finishes?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The late callbacks return [3, 3, 3, 3]; the early callbacks return [0, 1, 2, 3]. The invocation point stays after the loop.
One outer copy, shared inner rows
A shallow copy isolates outer-list assignments but not nested mutation. A deep copy can isolate the source while preserving aliases inside its own copied graph.
Understand first
The original output puzzle combines row mutation and row replacement. Each affects a different reference level.
Words you will see
- Outer slot
- An entry in the list that refers to a row.
- Deep copy
- Recursive copying of supported objects with a memo of already copied objects.
- Replacement
- Assigning a different reference to one slot.
Walk the original source in time order
The deep copy is taken before either edit. shallow[0].append(9) changes the first row shared with original. shallow[1] = [8] replaces only shallow's second slot. original's second row remains [2].
The three lists print as [[1, 9], [2]], [[1, 9], [8]], and [[1], [2]]. The final True concerns only their first row references, not the outer lists. Each observation follows from a specific edge in the reference graph.
Choose copy depth deliberately
For flat numeric rows, [list(row) for row in original] copies exactly the two container levels. For arbitrary graphs, deepcopy uses a memo to handle cycles and preserve repeated internal references. It does not promise to make every path independent.
For n total numeric cells and r rows, row copying takes O(n + r) work and slots. External resources such as locks or open handles are not ordinary values to clone. Prefer an explicit ownership model rather than presenting deepcopy as universal isolation.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
shallow = original.copy()Create a new outer list while sharing the two rows.
deep = deepcopy(original)Copy the original graph before edits.
shallow[0].append(9)Mutate the shared first row.
shallow[1] = [8]Replace one outer slot without changing original's second row.
Appending affects the shared first row, while assigning the second row replaces a reference only in the shallow copy. The deep copy was taken before mutation and retains its separate nested values.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Move the deep-copy point.
Try: Move deep = deepcopy(original) after the append.
deep now includes nine in its first row but is independent of later mutations.
Replace the first row.
Try: Change shallow[0].append(9) to shallow[0] = [9].
original keeps [1] and the final first-row identity check becomes False.
Before you move on
If the append happens before deepcopy, what does deep contain?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It contains [[1, 9], [2]]. A copy reflects state at the time it is created, not the earlier state from before the append.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Explain and implement
Predict the worked example before running it locally, then change one boundary input and explain the result without the reference.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: copy rows before extending one
Repair a shallow-copy bug without changing the original grid or retaining aliases between returned rows.
The contract
- rows is a finite list of integer lists; a nonempty grid has a valid nonnegative index.
- Return independent new row lists and append value only to the selected row. For [], return a new [].
- Preserve source values and row objects. Repeated source row references must become separate result rows.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal
from copy import deepcopy source = [[1], [2]] before = deepcopy(source) result = extend_row(source, 0, 9) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[1, 9], [2]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" - empty
from copy import deepcopy source = [] before = deepcopy(source) result = extend_row(source, 0, 9) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" - empty row
from copy import deepcopy source = [[]] before = deepcopy(source) result = extend_row(source, 0, 0) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[0]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" - repeated values
from copy import deepcopy source = [[1, 1], [1, 1]] before = deepcopy(source) result = extend_row(source, 1, 1) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[1, 1], [1, 1, 1]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" - last row
from copy import deepcopy source = [[0], [1], [2]] before = deepcopy(source) result = extend_row(source, 2, -1) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[0], [1], [2, -1]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" - aliased input rows
from copy import deepcopy source = [[3]] * 2 before = deepcopy(source) result = extend_row(source, 1, 4) assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [[3], [3, 4]] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert result is not source, "Outer result aliases input" assert all(row is not old for row in result for old in source), "A returned row aliases input" assert len({id(row) for row in result}) == len(result), "Returned rows alias each other" result[0].append(99) assert source == before and result[1] == [3, 4], 'Nested ownership leaked'
Why can deepcopy differ from this contract?
deepcopy normally preserves repeated internal aliases. This task reconstructs every row independently. For r rows and n total cells, reconstruction costs O(r + n) work and storage.
Guided: capture each callback's value
Build delayed callbacks that each remember the integer from their own iteration.
The contract
- values is a finite list of integers. Return a new list with one zero-required-argument callable per input.
- Calling callbacks after construction returns the corresponding values in input order, including repeats.
- Do not mutate or retain the caller's list as the source of later lookups; later input-list edits must not change captured integers.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- normal
from copy import deepcopy source = [0, 1, 2] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [0, 1, 2] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" - empty
from copy import deepcopy source = [] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" - repeated
from copy import deepcopy source = [4, 4, 1] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [4, 4, 1] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" - negative
from copy import deepcopy source = [-2, 0] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [-2, 0] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" - single
from copy import deepcopy source = [8] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [8] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" - later caller edit
from copy import deepcopy source = [3, 6] before = deepcopy(source) result = [call() for call in callbacks(source)] assert type(result) is list, "Wrong result type" assert source == before, "Caller input changed" expected = [3, 6] assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" built = callbacks(source) assert type(built) is list and all(callable(call) for call in built), "Return a list of callables" assert [call() for call in built] == before, "Delayed callbacks lost their captured values" assert [call() for call in built] == before, "Repeated invocation changed captured values" assert source == before, "Callback construction changed caller input" saved = callbacks(source) assert type(saved) is list and all(callable(call) for call in saved), 'Return callable list' source[:] = [99] assert [call() for call in saved] == [3, 6], 'Callbacks read changed caller storage'
Does capturing a mutable row as a default snapshot its contents?
No. Defaults capture references. The task uses immutable integers; a mutable capture needs an explicit copy-depth contract. Constructing n callbacks takes O(n) function objects and storage.
Transfer: report a probe and the remaining stream
Make consumption part of the result. Return whether a positive value was found and the values left after the first match.
The contract
- values is a finite integer list. Create a local iterator; do not mutate the caller's list.
- Return exactly (found_bool, remaining_list). Consume through the first positive value, excluding that match from remaining.
- If no positive value exists, return (False, []). Preserve duplicates and order in the unconsumed tail.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- middle match
from copy import deepcopy source = [0, 2, 3] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, [3]) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input" - empty
from copy import deepcopy source = [] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, []) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input" - no match
from copy import deepcopy source = [0, -1, 0] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (False, []) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input" - first match
from copy import deepcopy source = [1, 2, 2] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, [2, 2]) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input" - last match
from copy import deepcopy source = [-2, 0, 4] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, []) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input" - repeated tail
from copy import deepcopy source = [-1, 3, 0, 0, -2] before = deepcopy(source) result = probe_tail(source) assert type(result) is tuple, "Wrong result type" assert source == before, "Caller input changed" expected = (True, [0, 0, -2]) assert result == expected, "Wrong result value" def same_types(actual, expected): if type(actual) is not type(expected): return False if type(expected) in (list, tuple): return len(actual) == len(expected) and all(same_types(a, b) for a, b in zip(actual, expected)) if type(expected) is dict: return actual.keys() == expected.keys() and all(same_types(actual[key], value) for key, value in expected.items()) return True assert same_types(result, expected), "Wrong nested result type" assert type(result[0]) is bool and type(result[1]) is list, "Wrong component types" assert result[1] is not source, "Tail aliases caller input"
Why would creating a fresh iterator for the tail be wrong?
It would replay consumed values. One shared cursor records progress. The worst-case scan and returned tail use O(n) time and O(n) output space, with O(1) cursor state.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneCommunicate trade-offs
An iterator remembers progress. A consumer such as any can stop early after taking a value, leaving a shorter stream for the next consumer.
Understand first
A successful probe can remove the very record later processing expected to see. Trace consumption to explain where it went.
Words you will see
- Iterator
- An object that supplies successive values and retains its current position.
- Short circuit
- Stopping as soon as the answer is known.
- Exhaustion
- The state in which no further values remain.
Account for every consumed value
The first any reads zero, finds it false, then reads two and finds it positive. Two has already been consumed when any returns True. list(stream) therefore sees only three.
Calling list again gives an empty list because this iterator is exhausted. A list is reusable as a source of fresh iterators; an iterator is not automatically rewound. A probe cannot promise to be observational unless its API explicitly buffers or duplicates state.
Select an alternative under the memory constraint
Materialise once if the stream is finite and fits memory, then probe and process the saved list. Or combine detection and processing in a single pass so no record is lost. itertools.tee can buffer a growing gap between consumers; it is not free independent traversal.
For n remaining values, list consumes O(n) time and O(n) slots. any may stop early, but in the worst case it scans all remaining values. For an infinite stream with no match it never finishes, so state the finite-input assumption.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
stream = iter([0, 2, 3])Create one stateful cursor over three values.
found = any(value > 0 for value in stream)Consume zero and two, stopping at the first positive value.
remaining = list(stream)Consume the sole unvisited value, three.
print(list(stream))Show exhaustion rather than replaying the source.
For each answer, distinguish language guarantees from CPython implementation details and average-case complexity from worst-case behaviour. Explain what you would measure or test when the environment changes rather than asserting a universal performance rule.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove every match.
Try: Change the source to [0, -2, -3].
found becomes False and the remaining list is empty.
Match the first item.
Try: Change the source to [1, 2, 3].
Only one value is consumed by any; remaining is [2, 3].
Before you move on
For stream [0, 0, -1], what remains after any(value > 0 for value in stream)?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Nothing remains. The search must inspect all three values to return False, so the iterator is exhausted.
Review after the mock
Cleanup belongs in finally, but a return there can replace an earlier result or exception. Preserve the operation's outcome while releasing its resource.
Understand first
A function may appear to return from try yet display a different value. Follow the pending outcome through cleanup.
Words you will see
- Pending return
- A computed result waiting for finally to finish.
- Finally
- A block run while control leaves try, including exceptional exits.
- Suppression
- Replacing an error or result so it no longer reaches the caller.
Trace the exit path
The try computes seven. Before returning it, Python runs finally and appends closed to events. Because finally has no return, the pending seven survives. The output records both the successful value and evidence of cleanup.
A return in finally would establish a new outcome and replace the pending seven. It can also hide an exception from try. Avoid this unless overriding the outcome is an explicit and rare requirement.
Test failure without hiding it
Replace the try return with a ValueError and observe the actual error. finally still records cleanup before the exception propagates. To inspect that event deterministically, catch ValueError outside the function, not inside cleanup.
A context manager expresses the same lifetime boundary more clearly for real resources. Cleanup must also be correct if acquisition fails; release only successfully acquired resources. The event list is a sequential model, not an operating-system handle test.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
events = []Collect deterministic evidence of cleanup.
return 7Compute the pending successful outcome.
events.append("closed")Perform cleanup before that outcome leaves the function.
result = work()Receive seven because finally did not replace it.
Write down one misconception, one missing edge case and one topic to revisit. Schedule a later independent attempt rather than reading the answer repeatedly. The course reading milestone records reflection, not an interviewer certification.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Expose the override.
Try: Add return 9 after events.append inside finally.
The result becomes nine even though try returned seven.
Test error propagation.
Try: Replace return 7 with raise ValueError('bad input').
Cleanup runs and the actual run reports ValueError rather than a fabricated successful result.
Before you move on
If finally additionally returns nine, what reaches the caller and why?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Nine reaches the caller. The later return replaces the pending seven; the cleanup event alone does not determine the returned value.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.