Junior — 25 questions
These are asked in nearly every first-round Python interview and in most screening calls. Answer each out loud before opening it; an answer you can say in two or three sentences is what they want. Every one is covered in Modules 01–07.
JuniorWhat is the difference between a list and a tuple?
A list is mutable — you can append, remove and reassign items; a tuple is immutable and fixed-size. Because a tuple cannot change, it can be hashed, so it can be a dict key or set member; a list cannot. Use a tuple for a fixed record (a coordinate, a row), a list for a collection you build up.
What they are really testing: Whether you know mutability is the real distinction, not "tuples are faster".
JuniorIs Python pass-by-value or pass-by-reference?
Neither in the C++ sense — it is "pass by object reference" (or "call by sharing"). The function receives the same object the caller has. If the object is mutable (a list), changes inside the function are visible outside; if you rebind the parameter name to a new object, the caller is unaffected. So items.append(x) leaks out; items = [] does not.
What they are really testing: Whether you can predict what a function does to its arguments.
JuniorWhat does if __name__ == "__main__": do?
When a file is run directly, Python sets its __name__ to "__main__"; when it is imported, __name__ is the module name. The guard lets a file be both a script (the block runs) and an importable module (the block does not run), so importing your code never triggers its side effects.
JuniorWhat is the difference between == and is?
== compares values (it calls __eq__); is compares identity — whether both names point at the very same object. Use is only for singletons: None, True, False. Two equal strings or ints may or may not be the same object depending on interning, so is on them is a bug that appears only sometimes.
JuniorWhat is a dictionary and when would you use it?
A hash map from keys to values with O(1) average lookup, insertion and deletion. Keys must be hashable (immutable). Use it whenever you look things up by a key — counting occurrences, grouping records, caching, representing JSON. Since 3.7 it preserves insertion order.
JuniorWhat are *args and **kwargs?
They collect extra arguments: *args gathers positional arguments into a tuple, **kwargs gathers keyword arguments into a dict. The names are convention; the stars are the syntax. In a call, the same stars unpack a sequence or dict into arguments. They are how decorators forward everything to the wrapped function.
JuniorWhat is the mutable default argument problem?
Default values are evaluated once, at def time. def f(items=[]) creates one list shared by every call that omits the argument, so appends accumulate across calls. The fix is items=None and if items is None: items = [] inside the function.
What they are really testing: A classic; not knowing it suggests you have not been bitten by it yet.
JuniorHow do you handle exceptions in Python?
try around the risky code, except SpecificError for what you expect, optional else for the success path and finally for cleanup. Catch the narrowest type you can, never a bare except:, and do not swallow errors silently — log, re-raise, or return something meaningful.
JuniorWhat is a list comprehension? Give an example.
A one-expression way to build a list from an iterable with an optional filter: [x * 2 for x in nums if x > 0]. It replaces the create-loop-append pattern, reads as "what, from where, under what condition", and is usually faster. Dict and set comprehensions use the same shape with braces.
JuniorWhat is the difference between / and //?
/ is true division and always returns a float (7 / 2 == 3.5, 4 / 2 == 2.0). // is floor division: it rounds toward negative infinity, so 7 // 2 == 3 and -7 // 2 == -4, not -3.
JuniorWhat is None?
The single object that represents "no value". Functions without a return return it, dict.get returns it for a missing key, and many in-place methods (list.sort, append) return it — which is why x = items.sort() makes x None. Test for it with is None.
JuniorHow do you read a file line by line?
With with open(path, encoding="utf-8") as f: and for line in f:. The file object is an iterator, so lines are read one at a time and the file can be any size. with guarantees the file is closed even if an exception is raised. Strip the trailing newline with line.rstrip("\n").
JuniorWhat is the difference between a shallow and a deep copy?
A shallow copy (list(a), a[:], a.copy(), copy.copy) creates a new outer container whose items are the same objects as the original. A deep copy (copy.deepcopy) recursively copies everything. With nested lists, a shallow copy shares the inner lists — changing one changes "both".
JuniorWhat is a set and when would you use it?
An unordered collection of unique hashable items with O(1) membership tests and set algebra (union, intersection, difference). Use it to de-duplicate, and whenever you repeatedly ask "is x in this collection?" — a list answers that by scanning, a set by hashing.
JuniorWhat are f-strings?
String literals prefixed with f where {expression} is replaced with the expression's value, with an optional format spec: f"{price:.2f}", f"{n:,}", f"{name=}" for debugging. They are the modern replacement for % formatting and str.format, and faster than both.
JuniorWhat does enumerate() do?
It wraps an iterable and yields (index, item) pairs, optionally starting the index somewhere other than 0. It replaces for i in range(len(items)) followed by items[i], which is both clumsier and the source of most IndexErrors.
JuniorWhat is PEP 8?
The official Python style guide: 4-space indentation, snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants, 79/99-character lines, two blank lines between top-level definitions. Tools like black and ruff enforce it automatically; teams use them so reviews are about logic, not spacing.
JuniorHow do you swap two variables?
a, b = b, a. The right-hand side builds a tuple (b, a) first, then unpacks it into the names — no temporary variable needed. The same tuple unpacking is how functions return multiple values.
JuniorWhat is the difference between append and extend?
append(x) adds x as one item — if x is a list, you get a nested list. extend(iterable) adds each item of the iterable individually. a + b is like extend but returns a new list.
JuniorWhat is a lambda?
An anonymous single-expression function: lambda x: x * 2. Its purpose is to be passed to something — a key= for sorting, map, a callback — where a named def would be noise. Anything needing a statement, a docstring or a name should be a def.
JuniorHow is memory managed in Python?
By reference counting plus a cycle-detecting garbage collector. Every object tracks how many references point at it; when the count hits zero it is freed immediately. Reference cycles (a → b → a) cannot reach zero, so a separate collector finds and frees them periodically. You rarely manage memory by hand; you avoid holding references you do not need.
JuniorWhat is the difference between a module and a package?
A module is one .py file; a package is a directory of modules with an __init__.py. import os loads a module; from collections import Counter pulls a name from a package's module. Packages let large codebases be organised into namespaces.
JuniorWhat does range(5) produce?
A lazy sequence of 0, 1, 2, 3, 4 — the stop value is exclusive. It is not a list: it computes each value on demand, so range(10**9) uses no memory. range(start, stop, step) takes a start and a step, including negative steps.
JuniorWhat is the output of print(0.1 + 0.2 == 0.3) and why?
False. Floats are binary fractions and 0.1, 0.2 and 0.3 cannot be represented exactly, so the sum is 0.30000000000000004. Compare floats with math.isclose, and use decimal.Decimal or integer cents for money.
JuniorHow do you check the type of a variable?
type(x) returns the exact class; isinstance(x, SomeClass) is what you use in code because it also accepts subclasses and can take a tuple of types. isinstance(x, (int, float)) is the idiomatic "is it a number".
