Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 62 / INTERVIEW PREPARATION

Interview bank: Python foundations

A structured rehearsal with model explanations, evaluation signals and follow-up constraints. These are original representative questions, not a claimed company interview bank.

FoundationInterview 30 min core+20 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

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.

YOU WILL BE ABLE TO
  • Explain reasoning before implementation
  • Identify assumptions and edge cases
  • Assess an answer against explicit signals
ORIGINAL REPRESENTATIVE QUESTIONS

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. A function appends to a list parameter and then assigns that parameter a new list. Which changes can its caller observe?

Reveal answer and evaluation signals

Python passes object references by assignment. The parameter initially refers to the same list as the caller, so appending mutates their shared object. Assigning a different list to the parameter only rebinds that local name. It does not replace the object referenced by the caller's name.

How it works

An assignment evaluates its right hand side and binds a name to that object. Function entry binds local parameter names without cloning their arguments. A list method can change the existing object's contents, whereas a subsequent assignment changes the local binding. Object lifetime depends on remaining references, not on any one variable.

Mutation before rebindingPYTHON 3

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

Choose an explicit ownership contract: either mutate and document that behavior, or return a new collection. For small flat collections, constructing a copy at the boundary often makes a transformation easier to compose and test than a function with surprising side effects.

Pitfalls and edge cases

  • Calling this pass-by-reference incorrectly suggests a callee can rebind the caller's variable.
  • A shallow copy protects the outer list, not mutable objects nested inside it.
Look for
  • Distinguishes mutation from rebinding
  • Explains shared references
  • Does not describe automatic copying

Follow-up: How would you make the function leave a flat input list unchanged?

Start with items = list(items), then perform appends on that local copy and return it. For nested data, decide which levels require independent ownership; blindly deep copying can duplicate objects that were intentionally shared.

Interview-ready takeaway

Track names and objects separately: mutation changes a shared object, while assignment changes one binding.

2. Two independently constructed lists compare equal. When should you use ==, is, or an explicit sentinel?

Reveal answer and evaluation signals

Equality asks whether objects represent equal values according to their comparison methods. Identity asks whether both references name the same object. Independently allocated lists can therefore be equal but not identical. Use identity for None or an intentional sentinel, not for comparing strings or numbers.

How it works

The == operator participates in the rich comparison protocol, including reflected comparisons and NotImplemented handling. Its behavior can be defined by a class. Identity is not customizable and does not invoke equality. Interpreter caching of some immutable values can make mistaken identity tests appear successful, but caching is not the application's semantic contract.

Values and a missing sentinelPYTHON 3

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 equality for domain values such as identifiers and quantities. Reserve sentinels for API states that cannot be represented unambiguously by existing values. Keep a sentinel private so callers cannot accidentally pass it as ordinary input.

Pitfalls and edge cases

  • Using is with literals relies on implementation reuse rather than value semantics.
  • An overloaded equality method can be expensive, raise exceptions, or return a non-boolean result.
Look for
  • Separates identity and value
  • Uses is None appropriately
  • Recognizes custom equality

Follow-up: Why is a private object sentinel useful when None is a valid argument?

Create missing = object() once and test value is missing. A caller passing None then follows the supplied-value path. If values cross serialization boundaries, encode absence explicitly because object identity does not survive reconstruction.

Interview-ready takeaway

Compare values with equality and deliberate singleton markers with identity; never infer identity from coincidentally cached literals.

3. A configuration permits retries=0, but retries or 3 changes it to 3. Explain and repair the defaulting rule.

Reveal answer and evaluation signals

Zero is false in a truth test, so or returns the fallback even though zero is an intentional value. Default only when the value is None if None represents missing configuration. Truthiness is appropriate for emptiness checks, but it does not express every domain-specific notion of absence.

How it works

Python checks __bool__ when available, otherwise __len__, otherwise considers an object true. Built-in false values include None, False, numeric zero, and empty containers. The or operator evaluates its left operand's truth and returns an operand rather than necessarily returning a bool. This makes concise defaults potentially lossy.

Absent versus intentionally disabledPYTHON 3

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

Document which values disable a feature, which mean missing, and which are invalid. Validate negative retry counts separately from selecting a default. Explicit conditions are preferable to clever expressions when several falsy values have different meanings.

Pitfalls and edge cases

  • The string 'False' is true because it is nonempty; parse configuration strings deliberately.
  • A custom truth method must obey its protocol and can itself raise, so truth tests are not always trivial.
Look for
  • Identifies zero as falsy
  • Preserves meaningful empty values
  • Understands operand-returning or

Follow-up: Which methods determine truth for a user-defined object?

Implement __bool__ returning an actual bool for domain-specific truth. If only __len__ exists, zero length makes the object false. Avoid assigning surprising truth semantics to objects whose valid state should always be treated as present.

Interview-ready takeaway

Truthiness describes a protocol, not missingness. Preserve intentional zero and empty values with an explicit absence test.

4. Why does 0.1 + 0.2 differ from 0.3, and which representation would you choose for prices versus measured distances?

Reveal answer and evaluation signals

Most decimal fractions have no exact finite binary floating-point representation. The addition operates on nearby representable values, so exact equality can fail. Use Decimal constructed from decimal strings for decimal accounting rules, integer minor units when suitable, and floats with justified tolerances for approximate measurements.

How it works

A float has finite precision and rounds operations to representable binary numbers. math.isclose combines relative and absolute tolerances rather than fixing arithmetic. Decimal uses a configurable decimal context, while Fraction represents rational values exactly with potentially growing numerators and denominators. Each model has different performance and policy implications.

Choose arithmetic deliberatelyPYTHON 3

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

Specify rounding mode, scale, and rounding boundaries for money rather than assuming Decimal alone defines accounting policy. For measurements, derive absolute tolerance near zero and relative tolerance at larger magnitudes from the application's error budget.

Pitfalls and edge cases

  • Converting an existing float to Decimal preserves that float's approximation.
  • A large default tolerance can hide genuine errors; exact comparisons remain correct for integers and some precisely representable floats.
Look for
  • Explains binary representation
  • Distinguishes decimal and approximate domains
  • Chooses meaningful tolerances

Follow-up: Why is Decimal(0.1) different from Decimal('0.1')?

Decimal(0.1) captures the actual binary float value as a decimal expansion. Decimal('0.1') parses the intended decimal quantity directly. Accept decimal text at the input boundary when exact decimal intent matters.

Interview-ready takeaway

Representation, rounding policy, and comparison tolerance must fit the domain; changing syntax does not eliminate numerical error.

5. An algorithm uses // and % to split signed offsets into blocks. What happens for -7 with a block size of 3?

Reveal answer and evaluation signals

Integer floor division rounds toward negative infinity, not toward zero. Therefore -7 // 3 is -3 and -7 % 3 is 2. They satisfy dividend = quotient * divisor + remainder. For a positive divisor the remainder is nonnegative, which is useful for wrapping signed positions.

How it works

Python integers have arbitrary precision constrained by available memory. Integer // and % operate without routing through floating-point values. The remainder follows the divisor's sign when nonzero. The / operator instead produces a float for integer operands, introducing finite precision and possible overflow for sufficiently large values.

Signed block decompositionPYTHON 3

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 divmod when both quotient and remainder are needed and define whether block numbering uses floor or truncation semantics. Reject a zero block size explicitly at a user-input boundary, and generally require a positive block size for indexing.

Pitfalls and edge cases

  • int(a / b) truncates an already rounded float and can lose integer precision.
  • Porting remainder logic from another language can silently change behavior for negative operands.
Look for
  • Predicts negative floor division
  • States quotient-remainder invariant
  • Distinguishes / from //

Follow-up: Does converting a float division result to int implement safe arbitrary-sized integer division?

No. int truncates toward zero, and integer-to-float conversion can lose low bits or overflow. If truncation is required, derive the magnitude with integer operations and restore the sign while documenting the intended remainder convention.

Interview-ready takeaway

Floor division and modulo form a signed invariant. Keep integer algorithms in integer arithmetic and specify negative-input behavior.

6. Why can visually identical Unicode names compare unequal, and how should a program convert text to bytes?

Reveal answer and evaluation signals

A Python str stores Unicode code points, while bytes stores integer byte values. Visually identical text can have different code-point sequences, such as a precomposed accented letter versus a base letter plus combining mark. Encode and decode explicitly at boundaries, and normalize only according to a documented text policy.

How it works

Encoding maps text to a byte sequence under a named codec; decoding reverses that mapping when input is valid. Unicode normalization can produce a canonical representation for equivalent sequences. It does not solve all case, language, security, or grapheme-boundary problems, and compatibility normalization may erase distinctions important to some applications.

Canonical text and UTF-8PYTHON 3

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

Choose UTF-8 for a defined interchange format unless another protocol requires something else. Preserve original display text when appropriate and normalize a separate comparison key. Treat decoding failures as data-quality or protocol errors rather than silently discarding bytes.

Pitfalls and edge cases

  • errors='ignore' can remove meaningful content and create collisions.
  • Case folding and normalization do not guarantee that visually confusable identifiers are safe.
Look for
  • Distinguishes code points and bytes
  • Explains normalization
  • Handles encoding errors deliberately

Follow-up: Does len(text) always count user-perceived characters?

No. len(str) counts code points, not extended grapheme clusters. Combining marks and multi-code-point emoji can display as one perceived character. Cursor movement and display limits require grapheme-aware handling beyond naive indexing.

Interview-ready takeaway

Text, code points, grapheme clusters, and encoded bytes are distinct layers; define the boundary and comparison policy explicitly.

7. Choose containers for an ordered worklist, a fixed coordinate, unique tags, and records keyed by identifier. What complexities matter?

Reveal answer and evaluation signals

Use a list for indexed ordered values, a tuple for a fixed positional record, a set for uniqueness and membership, and a dict for key-to-value lookup. Lists have constant-time indexing and amortized constant-time append, but linear membership and middle insertion. Hash collections provide average constant-time lookup under ordinary conditions.

How it works

Lists store an ordered sequence of references with extra capacity for growth. Tuples fix their element references but do not freeze referenced objects. Sets and dictionaries use hashes and equality to locate entries, so their keys must satisfy the hash contract. Dictionary insertion order is guaranteed; set iteration order is not an output contract.

Four different collection contractsPYTHON 3

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

Start with required operations, ordering, duplicates, and mutation rather than selecting one fashionable container. A dictionary can preserve insertion order and uniqueness by key, but it does not automatically implement sorted range queries or arbitrary priority scheduling.

Pitfalls and edge cases

  • Worst-case hash lookup is not guaranteed constant time; collisions and expensive equality matter.
  • A tuple containing a list is not deeply immutable and cannot be hashed.
Look for
  • Connects container to access pattern
  • Qualifies hash lookup complexity
  • Understands tuple immutability limits

Follow-up: Why might a deque be better than a list for a FIFO queue?

deque supports efficient append and popleft at opposite ends. Removing index zero from a list shifts remaining references and is linear. Lists remain preferable when frequent random indexing is the primary operation.

Interview-ready takeaway

Container selection is an access-pattern decision; include ordering, mutability, hashing requirements, and worst-case limitations in the explanation.

8. Why do repeated calls to a function with cache=[] share data, and what is the correct default when callers may supply a list?

Reveal answer and evaluation signals

Default expressions are evaluated when the function definition executes, not each time the function is called. A mutable default list is therefore shared across calls that omit the argument. Use None as a missing marker when it is not otherwise meaningful, and create the list inside the function.

How it works

A function object retains its evaluated defaults. Calls with omitted arguments reuse those objects. This behavior applies to dictionaries, sets, and user-defined mutable objects as well as lists. Replacing a parameter locally does not change the stored default, but mutating the default object changes what subsequent calls receive.

Independent default accumulatorsPYTHON 3

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 returning a newly constructed result when accumulation does not need to be shared. If callers supply storage, state clearly whether the function mutates it. An explicit cache object or closure is generally easier to discover, reset, and synchronize than hidden default state.

Pitfalls and edge cases

  • items = items or [] loses a caller's intentionally supplied empty list.
  • Defaults such as timestamps also freeze a value at definition time even when the object is immutable.
Look for
  • Knows definition-time evaluation
  • Creates fresh state per call
  • Preserves caller-supplied empty lists

Follow-up: Is persistent state in a default argument always incorrect?

No, intentional memoization can reuse a default, but the persistence, memory growth, concurrency behavior, and reset mechanism must be deliberate. A named cache or a standard caching decorator usually communicates the design better.

Interview-ready takeaway

Defaults persist with the function object. Allocate per-call state inside the body and make any shared-state contract explicit.

9. Design a function whose source must be positional, whose limit must be named, and that rejects unknown options.

Reveal answer and evaluation signals

Use the slash marker to make source positional-only and the star marker to make limit keyword-only. Do not accept arbitrary **kwargs unless the API actually supports forwarding or extension. Python's argument binding then detects unsupported names and duplicate arguments before the function body performs work.

How it works

The call binder matches positional arguments, keyword arguments, and defaults against the signature. A slash ends the positional-only section; a bare star starts keyword-only parameters. Variadic positional arguments become a tuple and variadic keywords become a dictionary. Signature design can make invalid combinations unrepresentable before domain validation begins.

A constrained public signaturePYTHON 3

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

Keyword-only options improve readability for booleans and numeric controls that would be ambiguous positionally. Positional-only inputs can preserve the freedom to rename an implementation parameter without breaking keyword callers. Keep signatures aligned with the actual compatibility promises of the API.

Pitfalls and edge cases

  • Type annotations do not enforce argument value types at runtime.
  • Accepting and silently ignoring arbitrary keywords hides misspellings instead of providing useful compatibility.
Look for
  • Uses / and * correctly
  • Explains binding failures
  • Avoids needless flexible signatures

Follow-up: When are *args and **kwargs justified?

Use them for genuine variadic operations, carefully designed adapters, or wrappers that forward a known callable's signature. Preserve introspection metadata and validate unsupported options instead of treating flexibility as a substitute for an interface.

Interview-ready takeaway

A precise signature provides executable API constraints; binding rules and domain validation solve different classes of input errors.

10. Rewrite a loop that labels nonempty names with their original positions. When is a comprehension preferable?

Reveal answer and evaluation signals

Use enumerate to retain original positions, and filter names inside a list comprehension if the transformation is short and side-effect-free. A comprehension constructs a result eagerly. An explicit loop is clearer when the operation needs several branches, detailed error handling, logging, or multiple accumulators.

How it works

A list comprehension iterates its input, applies filters, and evaluates the output expression for surviving elements. In Python 3 its iteration variable does not leak into the containing scope. enumerate yields pairs without building a separate index list. Filtering before numbering would produce different positions than numbering before filtering.

Keep source positionsPYTHON 3

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

Optimize for the next reader's ability to see transformation and selection separately. A short comprehension often clarifies both. Extract a named helper or use a loop when nested comprehensions require substantial mental execution to understand which loop or filter applies.

Pitfalls and edge cases

  • Using a comprehension only for side effects creates a useless result list.
  • Filtering first and enumerating afterward changes the meaning from original position to result position.
Look for
  • Uses enumerate rather than manual indexing
  • Understands filter order
  • Distinguishes comprehension from generator

Follow-up: How would a generator expression change resource use and evaluation timing?

A generator computes values on demand and retains suspended iteration state instead of the full output. Exceptions from later elements occur during consumption. It is single-pass and still retains references to its input and any captured state.

Interview-ready takeaway

Comprehensions are concise eager transformations; choose loops or generators when control flow or consumption semantics require them.

11. A loop searches for the first invalid record. What does its else clause mean, and how can you avoid confusing it with an if?

Reveal answer and evaluation signals

A loop's else executes when iteration finishes without a break, including when the iterable is empty. It does not mean that the last condition was false. A return or exception also prevents reaching the else. Use it for search exhaustion when that meaning is clearer than maintaining a separate flag.

How it works

for obtains successive values from an iterator until it is exhausted. break exits the nearest loop without running its else suite, whereas continue advances that loop to its next iteration. Natural exhaustion transfers control to else. A nested loop has its own independent break and exhaustion behavior.

Search exhaustion is explicitPYTHON 3

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 a direct return from a small search function when it simplifies the contract. Loop else is useful when work after the loop needs the found value, but avoid it when teammates are likely to mistake it for a conditional branch.

Pitfalls and edge cases

  • Reading the loop variable after an empty loop can raise UnboundLocalError.
  • A break in an inner loop does not stop the outer loop or suppress the outer loop's else.
Look for
  • Explains no-break semantics
  • Handles empty input
  • Distinguishes break and continue

Follow-up: How do break and continue interact with nested loops?

Both statements apply only to the innermost enclosing loop. To terminate a multi-level search, often extract it into a function and return the result. Exceptions or explicit state can work but should not obscure ordinary control flow.

Interview-ready takeaway

Read loop else as 'no break occurred'; test empty input and nested control flow rather than inferring meaning from indentation alone.

12. Distinguish TypeError, ValueError, KeyError, IndexError, and SyntaxError when debugging a small parser.

Reveal answer and evaluation signals

TypeError indicates an unsupported operation or inappropriate type, while ValueError indicates an unacceptable value of an otherwise relevant kind. KeyError signals a missing mapping key and IndexError an invalid sequence index. SyntaxError arises while parsing code rather than from ordinary execution of a valid expression.

How it works

Exceptions propagate up the call stack until a matching handler is found. A handler can recover, translate the exception with an explicit cause, or let it continue. Exception categories communicate contracts, but exact messages are less stable. Code containing a syntax error cannot begin normal execution in that compilation unit.

Classify failures without hiding themPYTHON 3

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

Catch conversion failures where input is converted and report a meaningful validation error. Do not wrap unrelated business logic in the same try block: otherwise programming mistakes can be misclassified as bad input and become harder to diagnose.

Pitfalls and edge cases

  • A broad fallback can turn missing data or programming errors into plausible but wrong values.
  • Using assert for required input validation is unsafe because optimized execution can remove assertions.
Look for
  • Matches exception to failure category
  • Catches narrowly
  • Separates parsing and execution

Follow-up: Why should a parser not catch Exception and return zero for every failure?

Zero may be a legitimate value, so the fallback destroys information. A broad catch also masks bugs such as accidental indexing errors. Return an explicit validation result or raise a documented domain exception while preserving the original cause.

Interview-ready takeaway

Exception types identify failure contracts. Handle expected boundary failures narrowly and let unexpected defects remain observable.

13. What do negative indices and slices mean, and why is repeated string concatenation inside a loop often a poor construction strategy?

Reveal answer and evaluation signals

Negative indices count from the end, while slices select a half-open range and clamp out-of-range boundaries. Individual invalid indices raise IndexError. Strings are immutable; repeated concatenation may repeatedly allocate and copy. Collect fragments and join them when assembling many pieces, without relying on interpreter-specific concatenation optimizations.

How it works

A slice uses start, stop, and step, with defaults influenced by step direction. The stop position is excluded. Built-in list slicing creates a new outer list containing references to selected elements. String operations produce string values rather than modifying the original string, and a zero slice step is invalid.

Boundaries and assemblyPYTHON 3

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 slices when boundaries naturally express a small subsequence. For large streaming data, avoid materializing many slices and consider iterators. Use join when fragments are already strings, and explicitly convert non-string elements instead of expecting automatic coercion.

Pitfalls and edge cases

  • A list slice is shallow, so nested mutations may still affect the original.
  • Joining arbitrary objects raises TypeError; stringify according to a deliberate presentation or serialization policy.
Look for
  • Explains half-open slices
  • Separates index and slice bounds
  • Chooses join for many fragments

Follow-up: Is a sliced list independent of nested mutable elements?

Only the outer container is independent. A nested list remains shared by both slices unless separately copied. If nested ownership matters, build exactly the independent structure required rather than assuming slicing recursively duplicates everything.

Interview-ready takeaway

Slicing has safe boundary rules but shallow ownership. String construction should respect immutability and avoid repeated unnecessary copying.

14. Why does zip silently drop unmatched records, and how can you require two input sequences to have equal lengths?

Reveal answer and evaluation signals

Ordinary zip stops when its shortest input is exhausted. That behavior is useful for deliberate pairing but dangerous when every item must have a partner. Python 3.11 supports zip(..., strict=True), which raises ValueError when lengths differ during iteration instead of silently accepting truncated processing.

How it works

zip is a lazy iterator that asks each input iterator for one value per output tuple. It does not necessarily know lengths in advance. Strict mode detects unequal exhaustion while values are consumed, so earlier pairs may already have been yielded. Materializing paired input can separate validation from later side effects for bounded datasets.

Require complete pairingPYTHON 3

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 strict pairing when unequal lengths indicate corrupted or misaligned data. For large streams, define how partial processing is handled rather than buffering everything automatically. A preflight length check works only for sized inputs and does not replace synchronization of changing sources.

Pitfalls and edge cases

  • Constructing a strict zip without iterating it does not validate anything.
  • Retrying a consumed input iterator does not reconstruct the original records.
Look for
  • Understands shortest-input behavior
  • Uses strict zip
  • Recognizes lazy error timing

Follow-up: Does strict zip guarantee that no partial work occurred before a mismatch is detected?

No. Earlier pairs can be processed before unequal exhaustion is discovered. For bounded input, first build and validate the pairs, then perform effects. For streams, use transactional batches or an explicit partial-progress protocol.

Interview-ready takeaway

Strict zip detects alignment errors lazily; completeness validation and side-effect atomicity are separate design requirements.

15. How do membership tests differ between dictionaries, their values, and lists, and why can a missing-key read change a defaultdict?

Reveal answer and evaluation signals

Membership in a dictionary tests keys, not values. Checking dict.values() scans values, while key membership normally uses hashing. A defaultdict invokes its factory for a missing subscription and stores the result. Membership tests and get do not invoke that factory, so apparently similar reads can have different mutation effects.

How it works

Dictionary subscription delegates missing-key behavior to the mapping implementation. defaultdict implements a missing hook that calls its configured factory and inserts the returned object. get follows a non-inserting lookup path. Regular dictionaries raise KeyError for missing subscription, while their membership operator reports presence without retrieving a value.

Observational versus inserting lookupPYTHON 3

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 defaultdict when construction naturally groups or accumulates data. Use ordinary dictionaries or non-inserting reads for inspection paths where a typo must not allocate state. Choose Counter when the operation is counting and its count-specific operations match the required semantics.

Pitfalls and edge cases

  • Looking for a value with value in mapping accidentally searches keys instead.
  • Serializing after exploratory defaultdict subscriptions can persist empty entries that were never meaningful data.
Look for
  • Distinguishes key and value membership
  • Explains factory invocation
  • Avoids accidental read mutations

Follow-up: When would Counter be clearer than defaultdict(int)?

Counter directly communicates frequency counting, supplies missing zero counts, and supports operations such as most_common. Confirm how zero and negative counts should behave before relying on its arithmetic operations, which have specific filtering rules.

Interview-ready takeaway

Mapping operations differ in lookup target and mutation behavior. Choose the collection whose missing-value contract matches the task.

01

Run an honest rehearsal

A foundation answer explains a rule with a small counterexample. Start by saying which values are accepted and which object the caller still owns.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A default for missing configuration can accidentally erase a deliberate zero. State what missing means before choosing a short expression.

Words you will see

Contract
The accepted input and promised result, including side effects.
Truthiness
How an object behaves in an if condition.
Absence
A domain state such as None that says no value was supplied.

Say the rule before the expression

Here None means missing and zero means no retries. The conditional reads the identity test first. Only None takes the fallback three. The second branch preserves the supplied integer. No caller-owned collection is changed.

The shorter value or 3 asks whether value is false, not whether it is missing. Zero, False and empty containers are false too. That is a different contract. Negative values need separate validation if the domain forbids them.

Rehearse a small falsifying case

Trace None, zero and two separately. The output shows each input beside its selected count. Explain why the zero case distinguishes the two algorithms; merely showing two does not.

This selection uses constant extra storage and a fixed number of operations for these built-in inputs. A user-defined truth method can run arbitrary code, so do not generalise every truth test to free work. Stop here for the core rule: missing is not the same as false.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def retries(value):

    Bind a local parameter without copying or changing the argument.

  2. return 3 if value is None else value

    Choose three only for the explicit missing marker.

  3. for value in (None, 0, 2):

    Visit missing, deliberately disabled and positive configurations.

  4. print(0 or 3)

    Show the tempting expression erasing zero.

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 decision path for an explicit missing value

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. InputNone, zero and two are distinct states.
  2. ConditionIdentity with None selects only absence.
  3. ResultUse the default or preserve the caller's supplied value.
Predict before you run

What does retries(0) return?

Keep an intentional zeroPYTHON 3

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.

Try a different missing default.

Try: Change return 3 to return 5.

Only the None case changes; zero and two remain supplied values.

Inspect a second false value.

Try: Add False to the tuple.

It stays False, exposing why selection and validation are separate responsibilities.

Before you move on

A timeout permits zero and uses None for unspecified. What should the defaulting rule return for zero?

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

Return zero. An identity check against None selects only the unspecified state; zero is already a supplied value.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Use the rubric, not keyword matching

A foundation rubric asks whether you can separate equal contents from a shared object. An identity observation is evidence about references, not about memory addresses.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A copied worklist can look equal yet be safe to append to independently. A returned alias can silently change the caller's data.

Words you will see

Equality
A comparison of represented values using ==.
Identity
Whether two references point to one object, tested with is.
Shallow copy
A new outer container that still refers to its original elements.

Trace names and objects

left and alias initially point to one list. right is made by list(left), so it has its own outer slots with equal integers. Equality is true, but identity is false. Appending through alias changes the list named left, not right.

Use is for None and private singleton markers. Do not compare numeric or string values with is: interpreter reuse of immutable objects is not an application guarantee. An equality method can be customised and is not an identity test.

Turn the rubric into observations

A strong answer states equal values, separate outer objects and the caller-visible append. Each statement is supported by a different print. If a candidate says copying isolates all data, change an integer into a nested list to test that stronger claim.

For n entries, constructing this shallow list copy takes O(n) time and O(n) extra reference slots. Nested objects are not recursively cloned. Copy only the levels the ownership contract requires rather than saying every copy is deep.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. alias = left

    Create a second name for the same object.

  2. right = list(left)

    Allocate new outer list slots containing the same integer references.

  3. print(left == right, left is right)

    Observe matching contents and distinct objects before mutation.

  4. alias.append(3)

    Change the shared left object; right retains two entries.

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.

Predict before you run

Which object sees alias.append(3)?

Equal lists need not be aliasesPYTHON 3

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.

Compare after the append.

Try: Add print(left == right) at the end.

It prints False because their lengths and contents now differ.

Replace copying with aliasing.

Try: Change right = list(left) to right = left.

Both identity and equality start true, and both names show the append.

Before you move on

If right = left replaces the copy line, what do the final two prints show?

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

Both show [1, 2, 3]. The assignment creates another reference to left, so the append is visible through both names.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Mutation before rebinding

A function parameter starts as a local name for the supplied object. Mutation changes that object; rebinding the parameter changes only the local name.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The original bank example contains both operations. Explaining their order is stronger than repeating a slogan such as pass by reference.

Words you will see

Parameter
A local name bound when a function is called.
Mutation
A change to an existing object's contents.
Rebinding
Making a name refer to another object.

Walk the original source

original starts as [1]. On entry, items refers to that list. append(2) changes the shared object to [1, 2]. The next assignment creates [9] and makes only items refer to it. return items hands that separate list to result.

The prints therefore show [1, 2], [9], and False. The caller retains the original object throughout. The returned object is not automatically a copy of the input; it is the explicit list literal evaluated inside the function.

State the ownership alternative

To promise no outer-list mutation, first build a local list copy and append to it. To promise nested independence, specify which nested rows must be copied too. Neither ordinary argument passing nor rebinding clones an object.

For a flat list of n elements, that defensive copy costs O(n) time and space. Appending to a CPython list is amortized O(1), not a worst-case constant-time claim for every call. Returning the already built list does not copy its elements.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. original = [1]

    Give the caller one owned list.

  2. items.append(2)

    Mutate the object still visible through original.

  3. items = [9]

    Rebind the local parameter to a separate list.

  4. print(original is result)

    Observe False: the returned list is not the caller's list.

The caller sees the append because it still references the original object. The returned list is separate. Comparing identities confirms separation without exposing implementation-specific addresses or relying on integer interning.

Predict before you run

What does the caller's original contain in the unchanged program?

Mutation before rebindingPYTHON 3

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.

Rebind before mutating.

Try: Move items = [9] before items.append(2).

original stays [1], while result becomes [9, 2].

Remove the shared mutation.

Try: Delete items.append(2).

original stays [1], result stays [9], and identity is still False.

Before you move on

If the function assigns items = [9] before appending, what does original contain afterwards?

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 remains [1]. The append then acts on the newly assigned local list, so the returned result would be [9, 2].

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

What is the strongest next step after reading a model answer?
TRANSFER THE IDEA

Explain and implement

Predict the worked example before running it locally, then change one boundary input and explain the result without the reference.

Your practice starterPYTHON 3

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.

MAKE THE RULE WORK ON NEW INPUTS

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.

Return a value, do not only print itPYTHON 3

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

Guided: append without taking the caller's list

Return a fresh flat list with one appended value. Explain which object changes and why the caller's list does not.

The contract

  • items is a finite list of integers; value is an integer.
  • Return a new list preserving order and duplicates, followed by value; [] becomes [value].
  • Do not mutate items. Elements are immutable integers, so shallow outer copying is sufficient.
Guided: append without taking the caller's listPYTHON 3

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.

  1. normal
    from copy import deepcopy
    source = [1, 2]
    before = deepcopy(source)
    result = appended(source, 3)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [1, 2, 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 result is not source, "Result aliases caller input"
    
  2. empty
    from copy import deepcopy
    source = []
    before = deepcopy(source)
    result = appended(source, 5)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [5]
    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, "Result aliases caller input"
    
  3. duplicates
    from copy import deepcopy
    source = [2, 2]
    before = deepcopy(source)
    result = appended(source, 2)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [2, 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 result is not source, "Result aliases caller input"
    
  4. zero
    from copy import deepcopy
    source = [0]
    before = deepcopy(source)
    result = appended(source, 0)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [0, 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, "Result aliases caller input"
    
  5. negative
    from copy import deepcopy
    source = [-2, 1]
    before = deepcopy(source)
    result = appended(source, -1)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [-2, 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, "Result aliases caller input"
    
  6. fresh ownership
    from copy import deepcopy
    source = [9]
    before = deepcopy(source)
    result = appended(source, 8)
    assert type(result) is list, "Wrong result type"
    assert source == before, "Caller input changed"
    expected = [9, 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"
    assert result is not source, "Result aliases caller input"
    result.append(7)
    assert source == before, 'Returned list shares caller storage'
    
    Why is items = items not a copy, and what does a real copy cost?

    Assignment adds a reference to the same list. list(items) creates n new outer slots in O(n) time and space; appending then changes only that copy.

    GUIDED PRACTICE

    Guided: preserve a disabled retry value

    Normalise a sequence of optional retry counts without confusing zero with missing.

    The contract

    • values is a list of None or nonnegative exact integers; other inputs are outside this exercise's domain.
    • Return a fresh list replacing only None with 3. Preserve zero, order and duplicates.
    • Never change the caller's list; an empty input produces a new empty list.
    Guided: preserve a disabled retry valuePYTHON 3

    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.

    1. mixed
      from copy import deepcopy
      source = [None, 0, 2]
      before = deepcopy(source)
      result = retry_defaults(source)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [3, 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 result is not source, "Result aliases caller input"
      
    2. empty
      from copy import deepcopy
      source = []
      before = deepcopy(source)
      result = retry_defaults(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"
      assert result is not source, "Result aliases caller input"
      
    3. all missing
      from copy import deepcopy
      source = [None, None]
      before = deepcopy(source)
      result = retry_defaults(source)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [3, 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 result is not source, "Result aliases caller input"
      
    4. disabled
      from copy import deepcopy
      source = [0]
      before = deepcopy(source)
      result = retry_defaults(source)
      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, "Result aliases caller input"
      
    5. duplicates
      from copy import deepcopy
      source = [2, 2, 0]
      before = deepcopy(source)
      result = retry_defaults(source)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [2, 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"
      assert result is not source, "Result aliases caller input"
      
    6. large supplied
      from copy import deepcopy
      source = [1000000, None]
      before = deepcopy(source)
      result = retry_defaults(source)
      assert type(result) is list, "Wrong result type"
      assert source == before, "Caller input changed"
      expected = [1000000, 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 result is not source, "Result aliases caller input"
      
      Why is value or 3 wrong, and what is the cost of the repair?

      or replaces zero too. The explicit None condition preserves it. A single pass takes O(n) work and O(n) returned storage for n supplied counts.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: place signed offsets into blocks

      Change from reference reasoning to an arithmetic invariant. Return each offset's block number and in-block remainder.

      The contract

      • offsets is a finite list of integers and size is a positive exact integer.
      • Return a fresh list of (quotient, remainder) tuples in input order, including duplicates.
      • Each pair must satisfy offset = quotient * size + remainder and 0 <= remainder < size. Preserve offsets; [] returns [].
      Transfer: place signed offsets into blocksPYTHON 3

      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.

      1. signed
        from copy import deepcopy
        source = [-7, 0, 7]
        before = deepcopy(source)
        result = block_positions(source, 3)
        assert type(result) is list, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = [(-3, 2), (0, 0), (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, "Result aliases caller input"
        
      2. empty
        from copy import deepcopy
        source = []
        before = deepcopy(source)
        result = block_positions(source, 4)
        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, "Result aliases caller input"
        
      3. duplicates
        from copy import deepcopy
        source = [-1, -1]
        before = deepcopy(source)
        result = block_positions(source, 4)
        assert type(result) is list, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = [(-1, 3), (-1, 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 result is not source, "Result aliases caller input"
        
      4. unit size
        from copy import deepcopy
        source = [-3, 0, 3]
        before = deepcopy(source)
        result = block_positions(source, 1)
        assert type(result) is list, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = [(-3, 0), (0, 0), (3, 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, "Result aliases caller input"
        
      5. exact boundaries
        from copy import deepcopy
        source = [-8, 8]
        before = deepcopy(source)
        result = block_positions(source, 4)
        assert type(result) is list, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = [(-2, 0), (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"
        assert result is not source, "Result aliases caller input"
        
      6. inside boundary
        from copy import deepcopy
        source = [-1, 1]
        before = deepcopy(source)
        result = block_positions(source, 10)
        assert type(result) is list, "Wrong result type"
        assert source == before, "Caller input changed"
        expected = [(-1, 9), (0, 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, "Result aliases caller input"
        assert all(type(pair) is tuple and len(pair) == 2 for pair in result), 'Each position must be a pair'
        
        Which test rejects truncation, and what assumptions make the costs simple?

        Negative nonmultiples such as -7 distinguish floor from truncation. For n bounded-size integers this is O(n) arithmetic operations and output slots; large-integer arithmetic adds bit-length costs.

        A GOOD PLACE TO PAUSE

        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 milestone

        Communicate trade-offs

        A precise arithmetic answer states its rounding rule. Integer floor division and remainder describe a signed offset without losing its position.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Splitting negative offsets into fixed-size blocks fails if division is incorrectly assumed to truncate toward zero.

        Words you will see

        Floor
        The greatest integer no larger than a value.
        Quotient
        The whole-block part of a division.
        Remainder
        The part that completes offset = quotient * size + remainder.

        Use the equation as evidence

        With size three, -7 // 3 is -3, not -2. The remainder is two, so -3 * 3 + 2 reconstructs -7. With a positive divisor, the remainder is nonnegative and smaller than that divisor.

        divmod supplies the quotient and remainder together. Trace both values, then check reconstruction. Testing only positive offsets would not distinguish floor division from truncation.

        Name the boundary and cost

        This rehearsal accepts integer offsets and a positive integer block size. Zero size raises ZeroDivisionError and a negative size changes the remainder rule. State those constraints rather than hiding them in an example.

        For n fixed-size integers the loop uses O(n) arithmetic operations and O(1) extra working slots beyond displayed output. Arbitrarily large Python integers have bit-length-dependent arithmetic costs; count operations separately from claiming constant physical time.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. size = 3

          Choose a positive block width.

        2. for offset in (-7, 0, 7):

          Exercise signed, zero and positive boundaries.

        3. block, remainder = divmod(offset, size)

          Use floor division and its paired remainder.

        4. print(block, remainder, block * size + remainder == offset)

          Verify the invariant for each offset.

        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.

        Predict before you run

        What is divmod(-7, 3)?

        Signed offsets retain a reconstruction invariantPYTHON 3

        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 positive size.

        Try: Set size = 4.

        The negative case becomes (-2, 1); reconstruction stays true.

        Inspect the zero-size boundary.

        Try: Set size = 0.

        The actual run raises ZeroDivisionError; no reference output should replace that error.

        Before you move on

        For offset -1 and size four, which block and remainder reconstruct the offset?

        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

        Block -1 and remainder three: -1 * 4 + 3 = -1. Block zero would violate the nonnegative remainder rule.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Review after the mock

        A useful follow-up tests a changed requirement, not a memorised output. Fresh default state must be allocated at the ownership boundary.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A function with a list default can retain work between unrelated calls. Re-answering with an explicit caller-supplied list reveals whether the repair preserves intentional sharing.

        Words you will see

        Default expression
        An expression evaluated when a def statement executes.
        Lifetime
        How long an object remains reachable.
        Sentinel
        A deliberate marker for a special state such as omitted input.

        Separate fresh calls from intentional mutation

        None is the missing marker here. Each omitted argument reaches items = [] inside the call, allocating a fresh list. A supplied list bypasses that allocation and is deliberately appended to.

        The first two results do not accumulate. The explicit work list does accumulate the third value because that is the declared mutating contract. A blanket rule to copy every supplied argument would change this API.

        Make the next attempt independent

        After reading a model answer, hide it and explain why a list literal in the function header has a longer lifetime than one inside the body. Then test both omitted and explicit arguments. Those cases distinguish a genuine ownership explanation from memorised syntax.

        A None default is appropriate only if None is not valid supplied data. Otherwise use a private object sentinel and identity comparison. Reading progress and these public checks are rehearsal feedback, not hiring certification.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. def add(value, items=None):

          Use an immutable absence marker instead of a persistent default list.

        2. items = []

          Allocate only for an omitted list.

        3. items.append(value)

          Mutate the chosen list according to the contract.

        4. print(add(3, work))

          Demonstrate the explicit caller-owned path.

        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.

        Predict before you run

        Does the second omitted call include the first call's item?

        Fresh defaults and explicit caller ownershipPYTHON 3

        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.

        Test the empty supplied list.

        Try: Change work = [8] to work = [].

        The last two prints both show [3]; the caller's empty list was retained.

        Expose persistent default state.

        Try: Change items=None to items=[] and remove the if block.

        The second omitted call now shows [1, 2], because the header list survives between calls.

        Before you move on

        If work = [] is supplied, should add(3, work) leave work empty under this contract?

        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

        No. It must append to that supplied list. Testing identity with None preserves an empty caller-owned list instead of replacing it.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        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.

        REFLECT, THEN CONTINUE

        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.

        Your account

        Loading account...

        Sign in to save your work across devices.