Python Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. Which of these built-in types is immutable?

    Correct answer: tuple

    Tuples, strings, numbers and frozensets can't change after creation. Lists, dicts and sets can be modified in place.

  2. 2. What does this code print?

    a = [1, 2, 3]
    b = a
    b.append(4)
    print(a)

    Correct answer: [1, 2, 3, 4]

    Assignment doesn't copy. a and b are two names for the same list, so appending through b is visible through a.

  3. 3. What is the difference between == and is?

    Correct answer: == compares values, is checks that both names point to one object

    == calls __eq__ and compares content. is compares identity. Use is for singletons like None, and == for values.

  4. 4. How should you check that a variable is None?

    Correct answer: if x is None:

    None is a singleton, so PEP 8 recommends is None. == None usually works but can be fooled by a custom __eq__.

  5. 5. What does 7 // 2 return?

    Correct answer: 3

    // is floor division: it rounds down to the nearest integer. / always returns a float, so 7 / 2 is 3.5.

  6. 6. What does -7 // 2 return?

    Correct answer: -4

    Floor division rounds towards negative infinity, not towards zero. -3.5 rounded down is -4.

  7. 7. What does print(0.1 + 0.2 == 0.3) print?

    Correct answer: False

    Floats are binary fractions, so 0.1 and 0.2 can't be stored exactly and the sum is 0.30000000000000004. Compare with math.isclose or use decimal.

  8. 8. Which values are falsy in Python?

    Correct answer: 0, "", [], {} and None

    Zero of any numeric type, empty strings and containers, None and False are falsy. That's why if items: is the idiomatic emptiness check.

  9. 9. What does [1, 2, 3, 4, 5][1:4] return?

    Correct answer: [2, 3, 4]

    A slice starts at the first index and stops before the second. Index 1 is 2, and index 4 (the value 5) is excluded.

  10. 10. What does s[::-1] do with a string s?

    Correct answer: Returns a reversed copy of the string

    A step of -1 walks the sequence backwards. Strings are immutable, so a slice always builds a new string.

  11. 11. What happens when you run this code?

    s = "hello"
    s[0] = "H"

    Correct answer: A TypeError: strings don't support item assignment

    Strings are immutable. Build a new one instead, for example "H" + s[1:] or s.capitalize().

  12. 12. What is the idiomatic way to join a list of strings with commas?

    Correct answer: ",".join(items)

    join is a string method: the separator is the object and the iterable is the argument. Every item must be a string.

  13. 13. What does this f-string print?

    price = 3.14159
    print(f"{price:.2f}")

    Correct answer: 3.14

    After the colon comes a format spec. .2f means fixed-point with two digits after the decimal point.

  14. 14. What is the difference between list.append(x) and list.extend(x)?

    Correct answer: append adds x as one item, extend adds each item of x

    [1].append([2, 3]) gives [1, [2, 3]], while [1].extend([2, 3]) gives [1, 2, 3].

  15. 15. What does list.sort() return?

    Correct answer: None, because it sorts the list in place

    Methods that change an object in place return None by convention. Use sorted(items) when you need a new list.

  16. 16. How do you sort a list of words by length?

    Correct answer: sorted(words, key=len)

    key takes a function that is called once per item, and items are compared by its result. Add reverse=True for descending order.

  17. 17. What is the idiomatic way to loop over a list with indexes?

    Correct answer: for i, item in enumerate(items):

    enumerate yields (index, item) pairs and takes an optional start. range(len(items)) works too but reads worse.

  18. 18. What does zip([1, 2, 3], ["a", "b"]) produce when turned into a list?

    Correct answer: [(1, 'a'), (2, 'b')]

    zip stops at the shortest iterable. Pass strict=True to get an error on different lengths, or use itertools.zip_longest to pad.

  19. 19. What does range(2, 10, 3) produce?

    Correct answer: 2, 5, 8

    range(start, stop, step) starts at 2, adds 3 each time and stops before 10.

  20. 20. When does the else block of a for loop run?

    Correct answer: When the loop finishes without hitting break

    for ... else is handy for searches: break when found, and else handles the not-found case. It also runs for an empty iterable.

  21. 21. What does this list comprehension produce?

    [x * x for x in range(6) if x % 2 == 0]

    Correct answer: [0, 4, 16]

    The filter keeps 0, 2 and 4, and each is squared. The order is: expression, for clause, then the optional if.

  22. 22. How do you build a dict that maps each word to its length?

    Correct answer: {w: len(w) for w in words}

    A dict comprehension uses curly braces and key: value. Curly braces with a single expression make a set comprehension instead.

  23. 23. What does d.get("missing") return when the key is absent?

    Correct answer: None, or a default you pass as the second argument

    d[key] raises KeyError, while d.get(key, default) returns default (or None). Use it when a missing key is a normal case.

  24. 24. In what order does iterating over a dict return its keys?

    Correct answer: In insertion order, guaranteed since Python 3.7

    Dicts keep insertion order as part of the language spec since 3.7. Sets, however, still have no defined order.

  25. 25. Why can't a list be used as a dict key?

    Correct answer: Lists are mutable and not hashable

    Keys need a stable hash. A list's contents can change, so it has no __hash__. Use a tuple instead.

  26. 26. What is the fastest way to remove duplicates from a list of hashable items if order doesn't matter?

    Correct answer: list(set(items))

    A set keeps only unique items. If order matters, list(dict.fromkeys(items)) keeps the first occurrence of each.

  27. 27. What does {1, 2, 3} & {2, 3, 4} return?

    Correct answer: {2, 3}

    & is intersection. | is union, - is difference and ^ is symmetric difference.

  28. 28. How do you create an empty set?

    Correct answer: set()

    {} creates an empty dict for historical reasons, and () is an empty tuple. Only set() gives an empty set.

  29. 29. How do you create a tuple with one element?

    Correct answer: (1,)

    The comma makes the tuple, not the parentheses. (1) is just the number 1, and tuple(1) fails because 1 isn't iterable.

  30. 30. What is the Pythonic way to swap two variables?

    Correct answer: a, b = b, a

    The right side builds a tuple first, then it's unpacked into the names. No temporary variable needed.

  31. 31. What does first, *rest = [1, 2, 3, 4] assign to rest?

    Correct answer: [2, 3, 4]

    A starred target collects the remaining items into a list. It can appear once in any position, for example *init, last = items.

  32. 32. What does this code print?

    def add(item, items=[]):
        items.append(item)
        return items
    
    print(add(1))
    print(add(2))

    Correct answer: [1], then [1, 2]

    Default values are evaluated once, when the function is defined. All calls share one list. Use items=None and create the list inside.

  33. 33. What do *args and **kwargs collect in a function signature?

    Correct answer: Extra positional arguments into a tuple, extra keyword ones into a dict

    The names are a convention, the stars matter. They are often used to pass arguments through, as in f(*args, **kwargs).

  34. 34. What does a function without a return statement return?

    Correct answer: None

    Every call returns something. If the body never hits return (or uses a bare return), the result is None.

  35. 35. In which order does Python look up a name inside a function?

    Correct answer: Local, enclosing function, global, built-in

    This is the LEGB rule. The first scope that has the name wins, so a local variable can shadow a built-in like list.

  36. 36. What happens when you run this code?

    count = 0
    
    def inc():
        count += 1
    
    inc()

    Correct answer: An UnboundLocalError

    Assigning to a name anywhere in a function makes it local for the whole body, so count += 1 reads a local that has no value yet. global count fixes it.

  37. 37. What is nonlocal for?

    Correct answer: Rebinding a variable of the enclosing function from a nested one

    Without nonlocal, assigning inside the nested function creates a new local. global does the same for module-level names.

  38. 38. What is a limitation of lambda in Python?

    Correct answer: Its body is a single expression, no statements

    A lambda can't contain assignments, loops or return. For anything bigger, a named def is clearer.

  39. 39. What does if __name__ == "__main__": do?

    Correct answer: Runs the block only when the file is executed directly

    When run as a script, the module's __name__ is "__main__". When imported, it's the module name, so the block is skipped.

  40. 40. What does import math do the second time it runs in the same process?

    Correct answer: Takes the already loaded module from sys.modules

    Modules are executed once and cached. Repeat imports just bind the cached object to a name.

  41. 41. Why is from module import * discouraged?

    Correct answer: It hides where names come from and can shadow existing ones

    Readers and linters can't tell which names exist, and an import can silently overwrite a local name. PEP 8 advises against it.

  42. 42. What is a virtual environment for?

    Correct answer: Keeping a project's packages separate from other projects

    Each venv has its own site-packages, so two projects can use different versions of one library. Create it with python -m venv .venv.

  43. 43. Why run python -m pip install ... instead of just pip install ...?

    Correct answer: It installs into exactly the Python you invoked

    With several Pythons on a machine, a bare pip may belong to a different one. python -m pip removes that ambiguity.

  44. 44. What does PEP 8 recommend for indentation?

    Correct answer: 4 spaces per level

    Indentation is syntax in Python, and mixing tabs and spaces is an error in Python 3. Formatters like Ruff or Black apply 4 spaces automatically.

  45. 45. Which naming style does PEP 8 use for functions and classes?

    Correct answer: snake_case for functions, CapWords for classes

    Constants are UPPER_CASE, and a leading underscore marks a name as internal.

  46. 46. What is self in a method?

    Correct answer: The instance the method was called on, passed in first

    obj.method(x) is roughly Class.method(obj, x). self is only a convention, but everyone uses it.

  47. 47. What does __init__ do?

    Correct answer: Initializes a new instance after it has been created

    __new__ creates the object and __init__ sets it up. You almost never need to override __new__.

  48. 48. What does this code print?

    class Dog:
        tricks = []
    
    a, b = Dog(), Dog()
    a.tricks.append("sit")
    print(b.tricks)

    Correct answer: ['sit']

    tricks is a class attribute shared by all instances. Create per-instance lists in __init__ with self.tricks = [].

  49. 49. What is the difference between __str__ and __repr__?

    Correct answer: __str__ is for users, __repr__ is an unambiguous form for developers

    print and str() use __str__, and the REPL, debuggers and containers use __repr__. If only __repr__ exists, str() falls back to it.

  50. 50. What does super().__init__() do in a subclass?

    Correct answer: Calls the parent's __init__ so it can set up its part

    If a subclass defines __init__, the parent's version isn't called automatically. super() follows the MRO, so it also works with multiple inheritance.

  51. 51. What does isinstance(True, int) return?

    Correct answer: True

    bool is a subclass of int, so True == 1 and True + True == 2. Keep that in mind when validating numbers.

  52. 52. Why is isinstance(x, Base) usually better than type(x) == Base?

    Correct answer: It also accepts instances of subclasses

    Exact type checks break when someone passes a subclass. isinstance also takes a tuple of types.

  53. 53. What does "duck typing" mean in Python?

    Correct answer: Code relies on the methods an object has, not on its class

    "If it walks like a duck and quacks like a duck": a function that calls .read() works with any file-like object.

  54. 54. What does the else block of try do?

    Correct answer: Runs only if the try block raised no exception

    Code in else isn't protected by the except clauses, so errors there aren't caught by mistake. finally runs in every case.

  55. 55. When does the finally block run?

    Correct answer: Always, whether an exception happened or not

    It runs even after return or break in try. It's the place for cleanup like closing a connection.

  56. 56. Why is a bare except: a bad idea?

    Correct answer: It also catches KeyboardInterrupt and SystemExit

    A bare except catches every BaseException, so Ctrl+C or sys.exit() can be swallowed. Catch the specific exceptions you expect.

  57. 57. How do you raise an error when a function gets an invalid argument?

    Correct answer: raise ValueError("age must be positive")

    raise takes an exception instance. ValueError fits a value of the right type that is out of range, TypeError fits the wrong type.

  58. 58. Which exception does [1, 2, 3][5] raise?

    Correct answer: IndexError

    Sequences raise IndexError for an index out of range, and mappings raise KeyError for a missing key. Both inherit from LookupError.

  59. 59. Why open files with with open(...) as f:?

    Correct answer: The file is closed even if an error happens

    with calls the context manager's exit method on leaving the block. Without it, an exception may leave the file open.

  60. 60. What should you pass to open() when reading a text file to avoid platform-dependent surprises?

    Correct answer: encoding="utf-8"

    Without encoding, Python has historically used the locale's encoding, which differs on Windows. Binary mode returns bytes, not text.

  61. 61. Which module gives an object-oriented way to work with file paths?

    Correct answer: pathlib

    Path("data") / "users.json" builds paths portably, and methods like .read_text() and .exists() replace many os.path calls.

  62. 62. What does json.loads do?

    Correct answer: Parses a JSON string into Python objects

    loads and dumps work with strings, load and dump with file objects. JSON objects become dicts and arrays become lists.

  63. 63. What does print(2 ** 100) print?

    Correct answer: 1267650600228229401496703205376

    Python integers have arbitrary precision, so they don't overflow. Only floats are limited to 64 bits.

  64. 64. What does round(2.5) return?

    Correct answer: 2

    round uses banker's rounding: halves go to the nearest even number, so round(2.5) is 2 and round(3.5) is 4.

  65. 65. What does 1 < x < 10 mean in Python?

    Correct answer: 1 < x and x < 10

    Comparisons chain, and x is evaluated only once. That's why a == b == c also works as expected.

  66. 66. What does "" or "default" evaluate to?

    Correct answer: "default"

    or returns the first truthy operand or the last one, not a bool. Be careful: it also replaces valid falsy values like 0.

  67. 67. What is Python's conditional expression syntax?

    Correct answer: a if condition else b

    The condition sits in the middle. Keep it short; nested conditional expressions are hard to read.

  68. 68. What does grid = [[0] * 3] * 3 create?

    Correct answer: Three references to the same inner list

    Changing grid[0][0] changes every row. Build independent rows with [[0] * 3 for _ in range(3)].

  69. 69. What does copy.copy(nested_list) copy?

    Correct answer: The outer list only; inner lists are still shared

    A shallow copy creates a new container with the same items. Use copy.deepcopy to copy nested objects too.

  70. 70. What is the average time complexity of x in some_set?

    Correct answer: O(1)

    Sets and dicts are hash tables. x in some_list, by contrast, scans the list and is O(n).

  71. 71. What is pass used for?

    Correct answer: As a placeholder where a statement is required

    An empty block is a syntax error, so pass fills it. continue skips to the next iteration, and return exits a function.

  72. 72. What does a docstring do?

    Correct answer: Documents code and is available as __doc__

    The first string literal in a body becomes its docstring. help() and IDEs show it. PEP 257 describes the conventions.

  73. 73. What does match do in Python 3.10 and later?

    Correct answer: Compares a value against structural patterns

    Structural pattern matching can destructure sequences, dicts and objects. case _: is the catch-all.

  74. 74. How does pytest know that a function is a test?

    Correct answer: Its name starts with test in a test_*.py file

    pytest discovers tests by naming conventions and uses plain assert statements, rewriting them to show detailed failure messages.

  75. 75. How do you check in pytest that code raises an exception?

    Correct answer: with pytest.raises(ValueError):

    The test fails if the block doesn't raise. Add match="..." to check the message as well.