Gapfyre

Python interview questions

A Python interview rarely asks you to recite syntax. It asks what a generator actually is, why a default argument of [] bites, or what the bare * in a signature does — the things you use every day without having to say out loud.

These questions run from that first layer (lists against tuples, *args and **kwargs, shallow and deep copies) to the corners modern codebases lean on: pathlib, match, typing with Literal and Iterable.

All 31 are the free Foundation level of the Python topic in GapfyreSWE. Try each one before you open its answer.

  1. What is a Python generator and what keyword creates one?

    1. A built-in that creates random values, defined with @generator
    2. A function using yield that produces values lazily, one at a time
    3. A decorator that makes a regular function run asynchronously
    4. A class that extends list to generate values on demand, created with generate()
    Show the answer

    B. A function using yield that produces values lazily, one at a time

    A generator is a function that yields values one at a time using the yield keyword, pausing execution between yields. It returns a generator object (iterator). Generators are memory-efficient for large sequences because values are produced lazily rather than stored in memory all at once.

  2. What is the difference between a list and a tuple in Python?

    1. Lists are ordered; tuples are unordered
    2. Lists use less memory than tuples for the same data
    3. Lists are mutable; tuples are immutable
    4. Tuples can hold mixed types; lists cannot
    Show the answer

    C. Lists are mutable; tuples are immutable

    Lists are mutable — elements can be added, removed, or changed. Tuples are immutable — once created they cannot be modified. Tuples are slightly faster, can be used as dictionary keys (if their contents are hashable), and signal intent that the data should not change.

  3. What does duck typing mean in Python?

    1. All Python objects inherit from a common Duck base class
    2. Python converts objects to strings automatically when needed
    3. An object's suitability is determined by its methods and attributes, not its type
    4. Python uses dynamic typing, so all variables are typed as "duck" until assigned
    Show the answer

    C. An object's suitability is determined by its methods and attributes, not its type

    Duck typing is a concept where the type or class of an object is less important than the methods and attributes it defines. If an object has the required method, it can be used — "if it walks like a duck and quacks like a duck, it's a duck." Python does not require explicit interface declarations.

  4. What is the difference between *args and **kwargs in a Python function definition?

    1. Both collect the same arguments — the double asterisk just enforces keyword-only syntax
    2. *args unpacks a list into function arguments; **kwargs unpacks a dict
    3. *args collects keyword arguments; **kwargs collects positional arguments
    4. *args collects positional arguments; **kwargs collects keyword ones
    Show the answer

    D. *args collects positional arguments; **kwargs collects keyword ones

    *args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Together they allow a function to accept an arbitrary number of positional and keyword arguments, making APIs flexible and enabling decorator pass-through.

  5. What is the difference between a shallow copy and a deep copy of a Python object (e.g. via copy.copy() vs. copy.deepcopy())?

    1. They are identical; deepcopy is only a performance-optimized alias for copy
    2. A shallow copy shares nested objects with the original; a deep copy recursively copies them
    3. A deep copy shares references while a shallow copy is fully independent
    4. A shallow copy only works on immutable types; a deep copy is required for any mutable type
    Show the answer

    B. A shallow copy shares nested objects with the original; a deep copy recursively copies them

    A shallow copy creates a new outer container, but the elements inside it are the same objects (by reference) as in the original — so mutating a nested mutable object (like a list inside a list) through the copy also changes the original. A deep copy recursively copies every nested object too, producing a fully independent structure where nothing is shared with the original at any level, at the cost of more time and memory to construct.

  6. What is the syntax and result type of a Python dictionary comprehension, as opposed to a list comprehension?

    1. A dict comprehension uses square brackets like a list comprehension, differing only in the presence of a colon
    2. Dict comprehensions cannot include a conditional (if) clause, unlike list comprehensions
    3. They produce the same result type; the syntax difference is purely cosmetic
    4. A dict comprehension uses braces and key: value; a list comprehension uses brackets
    Show the answer

    D. A dict comprehension uses braces and key: value; a list comprehension uses brackets

    A dict comprehension uses curly braces with a key: value pair per iteration — {k: v for k, v in pairs} — and produces a dict. A list comprehension uses square brackets with a single expression per iteration — [v for v in items] — and produces a list. Both share the same underlying for/if clause structure, just wrapped in different brackets and producing a different container with correspondingly different element shapes (key-value pairs versus single values).

  7. What is a Python lambda, and how does it differ from a function defined with def?

    1. A lambda can only take zero arguments; def is needed for parameters
    2. Lambdas execute faster than def because they skip bytecode compilation
    3. A lambda is an anonymous single-expression function; def takes full bodies
    4. A lambda can contain multiple statements and a full body, like def
    Show the answer

    C. A lambda is an anonymous single-expression function; def takes full bodies

    A lambda is a small, anonymous, single-expression function — lambda x: x * 2 — that evaluates and returns exactly one expression, with no statements, no name of its own (unless assigned to a variable), and no docstring. A def function can contain any number of statements, multiple return points, a docstring, and default naming, making lambdas suited only for short, throwaway callbacks (like a key= function passed to sorted()) rather than general-purpose function definitions.

  8. In a Python try/except/else/finally block, what specifically runs in the else clause versus the finally clause?

    1. else and finally both run unconditionally regardless of whether an exception occurred
    2. else runs only if the try block raised nothing; finally runs unconditionally afterwards
    3. else runs only when an exception is caught; finally only runs when no exception occurs
    4. finally is skipped if the exception is unhandled; only else runs in that case
    Show the answer

    B. else runs only if the try block raised nothing; finally runs unconditionally afterwards

    The else clause runs only if the try block completed with no exception raised at all — it is a place to put code that should run on the success path but that you don't want the except block accidentally catching exceptions from. The finally clause runs unconditionally, whether the try block succeeded, raised a handled exception, or raised an exception that propagated past every except clause — making it the right place for cleanup that must always happen (like closing a file), regardless of outcome.

  9. What is the difference between an iterable and an iterator in Python?

    1. Only built-in types like lists and dicts can be iterables; only user-defined classes can be iterators
    2. An iterator can be re-used indefinitely from the start; an iterable is single-use
    3. An iterable can produce a fresh iterator each time; an iterator is single-use and raises StopIteration
    4. They are the same thing; "iterator" is just an informal name for any iterable object
    Show the answer

    C. An iterable can produce a fresh iterator each time; an iterator is single-use and raises StopIteration

    An iterable is any object that implements __iter__(), which returns an iterator — a list, a dict, a string, and many other objects are iterable, but calling iter() on them fresh each time is what actually produces a new iterator. An iterator is the object that implements __next__(), producing one value at a time and raising StopIteration when exhausted; unlike an iterable, an iterator is generally single-use — once exhausted, it stays exhausted, while a fresh iterator can always be obtained again from the original iterable.

  10. What does collections.Counter do, and what problem does it solve compared to manually counting occurrences with a plain dict?

    1. It is functionally identical to a plain dict, differing only in its repr() output
    2. It is a thread-safe lock used to prevent race conditions when incrementing a shared counter variable
    3. Counter can only count integers, not arbitrary hashable objects like strings or tuples
    4. A dict subclass that tallies frequencies, treats a missing key as 0, and adds most_common() for convenience
    Show the answer

    D. A dict subclass that tallies frequencies, treats a missing key as 0, and adds most_common() for convenience

    Counter is a dict subclass specialized for counting hashable items: Counter(some_iterable) tallies how many times each element appears in one call, and looking up a key that has never been seen returns 0 instead of raising a KeyError, so incrementing a fresh key needs no manual existence check. It also comes with convenience methods like most_common() for ranking by frequency, which manually maintaining a plain dict of counts does not give you without extra code.

  11. What is an f-string in Python, and what problem does it solve compared to older %-formatting or .format()?

    1. It embeds the expression in the literal, more concise than % or .format()
    2. An f-string only formats floating-point numbers, embedding no expressions
    3. f-strings work only with string literals, never with template variables
    4. f-strings are evaluated lazily at first use and then cached
    Show the answer

    A. It embeds the expression in the literal, more concise than % or .format()

    An f-string (f"Hello, {name}!") lets an expression be embedded directly inside a string literal, evaluated and interpolated in place at the point where it appears — more concise and readable than %-formatting's separate format-string-plus-tuple, or .format()'s indexed/named placeholders that are visually disconnected from the values being substituted. Because the expression sits right where the substitution happens, an f-string is generally easier to read and less error-prone (fewer chances to mismatch a placeholder with the wrong positional argument) than either older style.

  12. What does [x * 2 for x in nums if x > 0] do, and why is it preferred to the loop it replaces?

    1. Modifies nums in place, which is why the result does not need to be assigned to anything
    2. Returns a generator, so the doubling happens lazily as the result is iterated
    3. Builds a new list from the items passing the filter — clearer and faster than an accumulate-and-append loop
    4. Is compiled to a C loop by the interpreter, which is the only reason it runs faster
    Show the answer

    C. Builds a new list from the items passing the filter — clearer and faster than an accumulate-and-append loop

    It builds a new list by applying the expression to each item that passes the condition — the same as an empty list, a for loop and an append, in one expression. It is preferred because the shape says what is being produced before you read the details, it keeps the result in one place rather than accumulating into a variable declared earlier, and it is measurably faster since the append is done by the interpreter rather than by a method call per item. The caution is nesting: past two clauses the loop is clearer.

  13. What is a Python virtual environment and why is it used?

    1. A sandboxed process that prevents a running script from accessing the filesystem or the network at all
    2. A container image that bundles the interpreter together with the OS libraries needed for deployment
    3. A background process that automatically restarts a script whenever it crashes or exits unexpectedly
    4. An isolated set of installed packages per project, so dependencies do not conflict across projects
    Show the answer

    D. An isolated set of installed packages per project, so dependencies do not conflict across projects

    A virtual environment is an isolated Python installation with its own site-packages directory, created with venv (or tools like virtualenv), so that packages installed for one project do not affect the system Python or any other project's dependencies. This lets two projects on the same machine depend on different, even conflicting, versions of the same library without either one interfering with the other.

  14. One codebase writes def find(id: int) -> User | None, another -> Optional[User]. What is the difference?

    1. None: Optional[X] is shorthand for X | None, which Python 3.10 and later accept directly
    2. X | None is checked at runtime and raises TypeError, while Optional is only a hint for tools
    3. Optional allows any falsy value such as 0 or "", while X | None allows only None itself
    4. Optional means the argument may be omitted, while X | None means it may be passed as None
    Show the answer

    A. None: Optional[X] is shorthand for X | None, which Python 3.10 and later accept directly

    None: they are the same type, and Optional[int] == (int | None) is true. Optional[X] was always shorthand for "X or None", and from Python 3.10 the | union syntax can be used in annotations directly, so new code tends to write X | None and drop the import. Either way the hint only documents that None is a possible result — nothing checks it at runtime — and a type checker then insists that callers handle the None before using the value as a User.

  15. Shape defines @classmethod def unit(cls): return cls(1) and @staticmethod def helper(x). Square subclasses Shape. What does Square.unit() return, and what does helper receive?

    1. A Shape, since a classmethod is bound to the class it is defined in; helper receives the instance
    2. A Square, but only if Square overrides unit; helper receives self like any other method
    3. A Square, since cls is the class it was called on; helper receives no implicit argument
    4. An error, since classmethods cannot be called on subclasses; helper receives the class
    Show the answer

    C. A Square, since cls is the class it was called on; helper receives no implicit argument

    A classmethod receives the class it was called on as cls, so Square.unit() builds a Square — which is why alternative constructors are classmethods, and why they keep working in subclasses. A staticmethod receives no implicit first argument at all, neither instance nor class; it is a plain function kept in the class's namespace, and Square(3).helper(5) simply returned 10. Writing return Shape(1) in the constructor instead would hand every subclass a Shape.

  16. Code builds file paths with os.path.join and string slicing. What does pathlib.Path offer instead?

    1. Validation that the file exists, since constructing a Path raises FileNotFoundError otherwise
    2. Cross-platform strings, since a Path is a str subclass that rewrites backslashes on Windows
    3. Path objects joined with / that expose parts like suffix and parent, plus methods to read and glob
    4. Faster file access, since a Path keeps the file open and caches all of its contents after the first read
    Show the answer

    C. Path objects joined with / that expose parts like suffix and parent, plus methods to read and glob

    A Path is an object rather than a string: / joins parts (Path("/srv/app") / "data" / "users.csv"), and the pieces are attributes — .suffix was ".csv", .stem "users", .parent.name "data" — so nobody slices strings at the last dot or slash. It also carries the operations: read_text(), write_text(), exists(), mkdir(parents=True), glob("*.py"). It uses the right separator on each platform, and the functions that take paths accept a Path, so most of os.path is no longer needed.

  17. A module does log = logging.getLogger(__name__) and later log.debug("value %s", obj). Why __name__, and why the %s rather than an f-string?

    1. __name__ names the logger by module for configuration; %s defers formatting until it is emitted
    2. __name__ hides the module from the output; %s writes the value in the record's raw binary form
    3. __name__ makes the logger a singleton per process; %s is required because logging rejects f-strings
    4. __name__ sets the level from an environment variable; %s pads the value to a fixed width
    Show the answer

    A. __name__ names the logger by module for configuration; %s defers formatting until it is emitted

    getLogger(__name__) names the logger after the module — myapp.billing — so configuration can target a package or one module by its dotted name, and log lines say where they came from. Passing the value as an argument defers formatting until a handler actually emits the record: with DEBUG off, which it is by default since an unconfigured logger's effective level is WARNING, str(obj) was never called for the %s form, while the f-string built its message regardless. Linters such as Ruff flag f-strings in logging calls for this reason.

  18. What do the bare * in def f(a, *, flag=False) and the / in def g(a, b, /, c) do?

    1. * makes the remaining parameters required, and / makes the preceding ones read-only inside f
    2. Both mark optional parameters, with * for keywords that default to None and / for defaults of 0
    3. * collects extra positional arguments into a tuple, and / divides the arguments as a float
    4. After * parameters must be passed by keyword; before / they must be passed by position
    Show the answer

    D. After * parameters must be passed by keyword; before / they must be passed by position

    Parameters after a bare * are keyword-only: f(1, flag=True) works and f(1, True) is a TypeError, "f() takes 1 positional argument but 2 were given" — which stops a call site reading as an unexplained True. Parameters before / are positional-only: g(1, 2, c=3) works and g(a=1, b=2, c=3) fails with "got some positional-only arguments passed as keyword arguments". The first makes calls readable; the second leaves a function free to rename its parameters without breaking callers.

  19. A match on a colour has case RED: as its first case, with RED = 1 defined at module level. Why does it fail to compile, and how is a constant matched?

    1. Names in patterns are compared by identity, and 1 is not the same object as RED
    2. A bare name captures any value, so RED would match everything; use a dotted name such as Color.RED
    3. Module-level names are not visible inside a match statement, so RED must be passed in as a parameter first
    4. match only accepts literals, so a constant must be written out as case 1 instead of a name
    Show the answer

    B. A bare name captures any value, so RED would match everything; use a dotted name such as Color.RED

    In a pattern, a bare name is a capture, not a lookup: case RED: would bind any value to a new variable called RED, so it matches everything — and as a first case it makes the rest unreachable, which Python refuses: "name capture 'RED' makes remaining patterns unreachable". Placed last, it silently swallowed everything. A constant has to be a dotted name, such as case Color.RED:. The other patterns destructure: {"type": "point", "x": x, "y": y} if x == y and [first, *rest] both matched in the harness.

  20. A function only loops over its argument. Why do typed codebases annotate it items: Iterable[str], imported from collections.abc, rather than items: list[str]?

    1. Iterable[str] converts the argument to an iterator on entry, so a list passed in is consumed only once
    2. collections.abc types are checked on every call at runtime, while list[str] is only read by checkers
    3. list[str] cannot be used in annotations before Python 3.12, so collections.abc is the portable spelling
    4. Iterable takes any iterable — tuple, set, generator — and lets the checker stop the function mutating it
    Show the answer

    D. Iterable takes any iterable — tuple, set, generator — and lets the checker stop the function mutating it

    Annotate a parameter with the least the function needs. list[str] promises a list, so mypy rejected passing a tuple; Iterable[str] accepted a list, tuple, set, generator or range alike, and mypy flagged items.append(...) inside the function, since an Iterable promises only that it can be looped over. Nothing changes at runtime: the function received the caller's own list object. collections.abc holds these abstract types — Iterable, Sequence, Mapping, Callable and the rest — and they work with isinstance too: a dict and a read-only MappingProxyType were both a Mapping, while the proxy was not a dict. list[str] itself has worked in annotations since Python 3.9.

  21. What does json.loads(json.dumps({1: (2, 3)})) return, and why is it not equal to the original?

    1. {'1': [2, 3]}: JSON keys are strings, and its only array type comes back as a list
    2. A TypeError from dumps, since JSON cannot represent tuples or integer dictionary keys
    3. {1: [2, 3]}: the int key survives, and only the tuple turns into a list on the way
    4. {1: (2, 3)} unchanged, since json records each value's Python type alongside it
    Show the answer

    A. {'1': [2, 3]}: JSON keys are strings, and its only array type comes back as a list

    It returned {'1': [2, 3]}. JSON objects have only string keys, so json.dumps turned the int key 1 into "1", and JSON has one array type, so the tuple became a list; nothing records what either was, so json.loads cannot restore them. Other quiet changes: a dict with both 1 and "1" as keys was written as {"1": "a", "1": "b"} and came back holding only the last; a tuple key raised TypeError ("keys must be str, int, float, bool or None"); and float("nan") was written as NaN, which is not valid JSON, unless allow_nan=False makes it an error. Types beyond these — sets, datetimes, dataclasses — raise TypeError rather than change.

  22. A RateLimiter instance is used like a function: allow = RateLimiter(2), then allow(user). What makes an instance callable, and why use one instead of a closure?

    1. Assigning a function to self.__call__ in __init__; the instance then keeps its state in a closure
    2. A __call__ method on its class; the instance keeps its state in attributes a caller can read
    3. Any class with __init__ is callable; calling an instance runs __init__ again with new arguments
    4. Inheriting from types.FunctionType, which gives the instance the calling convention of a def
    Show the answer

    B. A __call__ method on its class; the instance keeps its state in attributes a caller can read

    A __call__ method on the class: allow(user) runs it with allow as self, and callable(allow) is True. An instance keeps its state as attributes, so allow.calls read 3 after three calls, where a closure's counter is hidden — the closure had no calls attribute — and the class can carry other methods, a repr and configuration. That is why class-based decorators, middleware and strategy objects use it. The method has to be on the class: setting p.__call__ = lambda: "hi" on an instance left callable(p) False, and p() raised "'Plain' object is not callable", since Python looks special methods up on the type rather than the instance.

  23. A function is annotated def open_it(path: str, mode: Literal["r", "w"]). What happens to open_it("a", "x"), and to m = "w" followed by open_it("a", m)?

    1. The checker rejects "x" but accepts m, since it holds "w"; at runtime the "x" call raises ValueError
    2. The checker rejects both: "x" is not allowed, and m is inferred as str; neither fails at runtime
    3. Both are accepted: Literal is documentation only, and checkers treat it the same as a plain str
    4. Both raise TypeError at the call, because Literal is the one annotation the interpreter enforces
    Show the answer

    B. The checker rejects both: "x" is not allowed, and m is inferred as str; neither fails at runtime

    Literal narrows a type to specific values, so mypy rejected the first call: Argument 2 has incompatible type "Literal['x']"; expected "Literal['r', 'w']". At runtime nothing checks it — the same call ran and returned 'x'. The second call surprises people: mypy rejected it too, because m = "w" infers m as str, which could be any string. Annotating m: Final = "w" or m: Mode = "w" keeps the literal type, and both passed. Literals are how string and int options are typed — modes, log levels, HTTP methods — and a checker treats them like an enum: an if/elif covering both values needed no fallback return, and adding a third value made mypy report "Missing return statement". typing.get_args returns the values, ('r', 'w'), for code that wants to validate at runtime.

  24. Which line gives every Order its own empty items list when none is passed in?

    from dataclasses import dataclass, field
    
    @dataclass
    class Order:
        id: str
        ___
    1. items: list[str] = []
    2. items: list[str] = field(default_factory=list())
    3. items: list[str] = field(default=[])
    4. items: list[str] = field(default_factory=list)
    Show the answer

    D. items: list[str] = field(default_factory=list)

    A default is evaluated once, when the class is defined, so a [] default would be one list shared by every instance — the mutable-default bug a plain def __init__(self, tags=[]) still has: appending through one instance showed up in the next. @dataclass refuses it as the class is defined: "mutable default <class 'list'> for field items is not allowed: use default_factory", and field(default=[]) raised the same. default_factory takes a zero-argument callable that is called for each new instance, so two Orders had separate lists. Passing list() instead of list hands it an already-built list: the class was defined, then Order("1") failed with "'list' object is not callable". Dict and set defaults are refused the same way.

  25. A script reads its settings with tomllib.load(open("pyproject.toml")) and fails with TypeError. What is wrong, and what can tomllib not do?

    1. The file must be opened with encoding="utf-8"; and tomllib cannot parse nested [tool.*] tables
    2. load needs a binary file, open(..., "rb"); and tomllib only parses, with no dump to write TOML
    3. pyproject.toml is reserved for build tools; tomllib reads only other .toml files and never writes
    4. tomllib needs a str path, not a file object; and it cannot read TOML dates, which stay as strings
    Show the answer

    B. load needs a binary file, open(..., "rb"); and tomllib only parses, with no dump to write TOML

    tomllib.load takes a file opened in binary mode — "File must be opened in binary mode, e.g. use open('foo.toml', 'rb')", even with encoding="utf-8" given — because it decodes the bytes as UTF-8 itself, TOML being UTF-8 by definition. with open("pyproject.toml", "rb") as f: worked, and tomllib.loads takes a str, such as Path(...).read_text(). The result is plain dicts, lists and scalars, with TOML dates as datetime objects. tomllib only reads: it has no dump or dumps, so writing TOML needs a third-party package. It is in the standard library from Python 3.11 — on 3.9 the import raised ModuleNotFoundError — and code supporting older versions falls back to import tomli as tomllib, which behaved the same.

  26. A library that supports Python 3.9 and later imports override and TypeIs from typing_extensions rather than typing. What is typing_extensions, and why import from it?

    1. The older name of the typing module, kept so that code written for Python 2 still imports cleanly
    2. A type-checker plugin; the import is skipped at runtime, so it costs nothing and needs no install
    3. A standard-library module of experimental typing features, shipped with Python from 3.8 onwards
    4. A PyPI package backporting newer typing names, so one import works on every supported version
    Show the answer

    D. A PyPI package backporting newer typing names, so one import works on every supported version

    It is a package on PyPI — not part of the standard library, so it is a declared dependency — that backports new typing features to older Pythons. typing had no override on 3.9 or 3.11 and no TypeIs on 3.12, while typing_extensions provided both on 3.9 and on 3.12, so the library writes one import that works on every Python it supports. Where typing already has the name, it usually re-exports the standard object — on 3.14 typing_extensions.override is typing.override was True — though some it reimplements to carry newer behaviour: its TypedDict was not typing's on 3.14 or 3.12. Type checkers understand both spellings, and override works at runtime too, setting __override__ on the method.

  27. Which line completes this, so capitals maps each city back to its country code?

    codes = {"GB": "London", "FR": "Paris"}
    ___
    1. capitals = {city: code for code, city in codes.items()}
    2. capitals = dict(zip(codes, codes.values()))
    3. capitals = {city: code for code, city in codes}
    4. capitals = {city: code for city, code in codes.items()}
    Show the answer

    A. capitals = {city: code for code, city in codes.items()}

    items() yields (key, value) pairs, so unpacking them as code, city and writing city: code swaps each pair. Unpacking them as city, code just renames them, so the dict comes out unchanged, and zip over the keys and values rebuilds the original too. Iterating the dict itself yields only its keys, so each two-letter code is unpacked into its two characters: {'B': 'G', 'R': 'F'}.

  28. Which line completes this, so label is "£1,234.50"?

    price = 1234.5
    ___
    1. label = f"£{price:.2f}"
    2. label = f"£{price:,.2f}"
    3. label = f"£{price:2f,}"
    4. label = f"£{price:,}"
    Show the answer

    B. label = f"£{price:,.2f}"

    After the colon in an f-string comes a format spec. A comma adds thousands separators, and .2f gives fixed-point with exactly two decimals, in that order: ,.2f. Without the comma you get £1234.50, and without .2f the float prints as it is, £1,234.5. The parts must come in the order the spec defines, separator before precision, so 2f, raises ValueError: Invalid format specifier.

  29. Which line completes this, so top is [("the", 3)]?

    words = "the cat the dog the end".split()
    ___
    1. top = Counter(words).most_common()[0]
    2. top = sorted(Counter(words))[:1]
    3. top = max(Counter(words))
    4. top = Counter(words).most_common(1)
    Show the answer

    D. top = Counter(words).most_common(1)

    Counter tallies the words, and most_common(n) returns a list of the n commonest (item, count) pairs, highest first. most_common()[0] is the right pair, but as a tuple rather than a one-item list. max over a Counter compares its keys, the words themselves, so it returns the alphabetically largest word, here "the" by coincidence, without a count. sorted(...)[:1] takes the alphabetically first word, "cat".

  30. Which decorator completes this, so Temp.from_fahrenheit(212) gives a Temp at 100 °C, and a subclass's call gives an instance of the subclass?

    class Temp:
        def __init__(self, celsius):
            self.celsius = celsius
    
        ___
        def from_fahrenheit(cls, f):
            return cls((f - 32) * 5 / 9)
    1. @staticmethod
    2. @contextlib.contextmanager
    3. @property
    4. @classmethod
    Show the answer

    D. @classmethod

    @classmethod passes the class the method was called on as cls, so cls(...) builds a Temp from Temp and a subclass from a subclass. That is what makes it the usual way to write an alternate constructor. @staticmethod passes nothing implicit, so 212 lands in cls and f is missing: TypeError. @property makes Temp.from_fahrenheit a property object, which cannot be called. @contextmanager wraps it as a plain function, missing its argument the same way.

  31. A try statement has except, else and finally clauses, and the try body raises nothing. Put the parts that run in order.

    • The else block
    • The finally block
    • The try block
    Show the answer
    1. The try block
    2. The else block
    3. The finally block

    With no exception, the except clause is skipped. The else clause runs next, which is its whole point: code that should only run if the try succeeded, kept outside the try so its own errors are not caught by that except. finally runs last, whatever happened, including after a return or an uncaught exception.

Practise the rest in the app

GapfyreSWE has 53 more Python questions at Intermediate and Advanced level, and over 4,700 across 80+ topics. It works offline and asks for no account.

Download on the App Store Get it on Google Play

More topics