HireHireInterview Quizzes › Python Developer

Python Developer Interview Questions

Think you're ready? These are the questions that actually decide Python Developer interviews. Warm up on Easy — then face the Hard round, where 95% of candidates crumble. 79 questions across 3 levels, instant score, completely free.

79Questions
3Difficulty levels
95%Fail the hard round
FreeInstant score
Easy
Warm-up · 20 Qs
Medium
Practical · 29 Qs
Hard
Brutal · 30 Qs
⚡ Take the Python Developer quiz — get your score →

The Python Developer interview questions

Below are the real questions, grouped by difficulty. Expand any one to reveal the correct answer and why — or take the timed quiz for a score you can share. Can you clear the Hard round?

Easy round 20 questions

What is printed by `print(2 ** 3 ** 2)`?
  • A. 64
  • B. 512 ✓
  • C. 256
  • D. 12
Correct answer: B. The ** operator is right-associative, so it evaluates 3**2=9 first, then 2**9=512.
Given `a = [10, 20, 30]`, what does `a[-1]` return?
  • A. 10
  • B. 30 ✓
  • C. 20
  • D. An IndexError
Correct answer: B. A negative index counts from the end, so -1 refers to the last element, 30.
With `def f(x, items=[]): items.append(x); return items`, what does the second call `f(2)` return after calling `f(1)` first?
  • A. [2]
  • B. [1, 2] ✓
  • C. [1]
  • D. []
Correct answer: B. A mutable default argument is created once and persists across calls, so the list retains 1 and appends 2.
What happens when you run `if []: print('hi')`?
  • A. Prints hi
  • B. Prints nothing ✓
  • C. Raises a TypeError
  • D. Raises a ValueError
Correct answer: B. An empty list is falsy, so the condition is False and the block does not run.
What is the result of `t = (1, 2, 3); t[0] = 9`?
  • A. Sets the first element to 9
  • B. Raises a TypeError ✓
  • C. Returns None
  • D. Creates a new tuple
Correct answer: B. Tuples are immutable, so item assignment raises a TypeError.
Given `d = {'a': 1}`, what does `d.get('b')` return?
  • A. Raises a KeyError
  • B. Returns None ✓
  • C. Returns 0
  • D. Returns 'b'
Correct answer: B. Unlike d['b'], the get() method returns None for a missing key instead of raising KeyError.
Given `name = 'Sam'`, what does `f"Hi {name}"` produce?
  • A. "Hi Sam" ✓
  • B. "Hi {name}"
  • C. "Hi name"
  • D. Raises an error
Correct answer: A. An f-string substitutes the value of the expression inside the braces, yielding 'Hi Sam'.
Given `s = 'python'`, what does `s[1:4]` return?
  • A. "pyt"
  • B. "yth" ✓
  • C. "ytho"
  • D. "tho"
Correct answer: B. Slicing starts at index 1 and stops before index 4, giving characters at positions 1, 2, 3.
What is the value of `len(range(0, 10, 2))`?
  • A. 4
  • B. 5 ✓
  • C. 6
  • D. 10
Correct answer: B. range(0,10,2) yields 0,2,4,6,8, which is 5 values.
What does `7 / 2` evaluate to in Python 3?
  • A. 3
  • B. 3.5 ✓
  • C. 4
  • D. 3.0
Correct answer: B. The single-slash operator performs true division and returns the float 3.5.
Given `a = [1, 2]` and `b = [1, 2]`, what are `a == b` and `a is b`?
  • A. True and True
  • B. True and False ✓
  • C. False and True
  • D. False and False
Correct answer: B. == compares values (equal), while is compares object identity (two distinct list objects).
What is `len(set([1, 1, 2, 3, 3]))`?
  • A. 5
  • B. 3 ✓
  • C. 4
  • D. 2
Correct answer: B. A set removes duplicates, leaving the distinct values 1, 2, 3.
What happens when you run `s = 'abc'; s[0] = 'A'`?
  • A. Changes s to 'Abc'
  • B. Raises a TypeError ✓
  • C. Returns 'A'
  • D. Raises a KeyError
Correct answer: B. Strings are immutable, so assigning to an index raises a TypeError.
What does `[x * 2 for x in range(4)]` produce?
  • A. [0, 2, 4, 6] ✓
  • B. [2, 4, 6, 8]
  • C. [0, 1, 2, 3]
  • D. [0, 2, 4, 6, 8]
Correct answer: A. range(4) gives 0,1,2,3 and each is doubled to 0,2,4,6.
What is the result of `10 / 0`?
  • A. Returns 0
  • B. Returns infinity
  • C. Raises a ZeroDivisionError ✓
  • D. Returns None
Correct answer: C. Dividing by zero raises a ZeroDivisionError in Python.
In a `try / except / finally` block, when does the `finally` clause run?
  • A. Only if no exception occurs
  • B. Only if an exception occurs
  • C. Always, regardless of an exception ✓
  • D. Only if the except is missing
Correct answer: C. The finally block always executes, whether or not an exception was raised.
Inside `def f(*args): ...`, what type is `args`?
  • A. list
  • B. tuple ✓
  • C. dict
  • D. set
Correct answer: B. The *args syntax collects extra positional arguments into a tuple.
After `a = [[1, 2]]; b = a.copy(); b[0].append(3)`, what is `a`?
  • A. [[1, 2]]
  • B. [[1, 2, 3]] ✓
  • C. Unchanged from before
  • D. Raises an error
Correct answer: B. copy() makes a shallow copy, so the inner list is shared and the append affects both.
What is the result of `'abc' + 1`?
  • A. 'abc1'
  • B. Raises a TypeError ✓
  • C. 'abc'
  • D. 1
Correct answer: B. You cannot concatenate a string and an int, so this raises a TypeError.
After `x = [3, 1, 2]; y = sorted(x)`, what is the value of `x`?
  • A. [1, 2, 3]
  • B. [3, 1, 2] ✓
  • C. None
  • D. [3, 2, 1]
Correct answer: B. sorted() returns a new sorted list and leaves the original list unchanged.

Medium round 29 questions

You have a list of dictionaries and want to sort them by the 'age' key in descending order. Which is the correct approach?
  • A. sorted(people, key='age', reverse=True)
  • B. sorted(people, key=lambda p: p['age'], reverse=True) ✓
  • C. people.sort(by=lambda p: p['age'], desc=True)
  • D. sorted(people, lambda p: -p['age'])
Correct answer: B. sorted() takes a callable key function and a reverse boolean, so a lambda extracting p['age'] with reverse=True is correct.
What is the result of the following code? x = [1, 2, 3] y = x y.append(4) print(x)
  • A. [1, 2, 3]
  • B. [1, 2, 3, 4] ✓
  • C. [4, 1, 2, 3]
  • D. Raises an error
Correct answer: B. y = x binds both names to the same list object, so appending through y also affects x, printing [1, 2, 3, 4].
In a Python function, why is using a mutable default argument like def f(items=[]) considered a common bug?
  • A. The default list is created once and shared across all calls, so it accumulates values ✓
  • B. Python forbids lists as default arguments and raises a SyntaxError
  • C. The list is recreated on every call, wasting memory
  • D. It makes the function run slower on each call
Correct answer: A. Default arguments are evaluated once at function definition, so a mutable default persists and accumulates state across calls.
Which statement correctly opens a file for reading and guarantees it is closed afterward, even if an exception occurs?
  • A. f = open('data.txt'); f.read(); f.close()
  • B. with open('data.txt') as f: data = f.read() ✓
  • C. f = open('data.txt', 'r'); data = f.read
  • D. open('data.txt').read().close()
Correct answer: B. The with statement uses the file as a context manager, ensuring the file is closed automatically even if an exception is raised inside the block.
What does the following list comprehension produce? [x*x for x in range(5) if x % 2 == 0]
  • A. [0, 1, 4, 9, 16]
  • B. [0, 4, 16] ✓
  • C. [1, 9]
  • D. [0, 2, 4]
Correct answer: B. It squares only the even numbers 0, 2, and 4 from range(5), yielding [0, 4, 16].
You need to catch a specific exception when converting user input to an integer with int(user_input). Which exception should you catch?
  • A. TypeError
  • B. ValueError ✓
  • C. KeyError
  • D. RuntimeError
Correct answer: B. int() raises ValueError when the string cannot be interpreted as an integer, such as int('abc').
What is the primary purpose of a Python virtual environment (venv)?
  • A. To speed up the execution of Python scripts
  • B. To isolate project-specific dependencies from other projects and the system Python ✓
  • C. To compile Python code into a standalone binary
  • D. To automatically format code according to PEP 8
Correct answer: B. A virtual environment isolates a project's installed packages so different projects can have different, non-conflicting dependency versions.
Given d = {'a': 1, 'b': 2}, which expression safely returns 0 when the key 'c' is missing instead of raising an error?
  • A. d['c']
  • B. d.get('c', 0) ✓
  • C. d.fetch('c', 0)
  • D. d['c'] or 0
Correct answer: B. dict.get('c', 0) returns the default 0 when the key is absent, while d['c'] would raise a KeyError.
What is the difference between the == operator and the is operator in Python?
  • A. == compares object identity; is compares values
  • B. == compares values (equality); is compares object identity (same object in memory) ✓
  • C. They are identical and interchangeable
  • D. is works only on numbers; == works only on strings
Correct answer: B. == checks whether two objects have equal values, while is checks whether they are the exact same object in memory.
In a Python module, what does the guard if __name__ == '__main__': accomplish?
  • A. It ensures the file only runs on the main thread
  • B. It runs the enclosed code only when the file is executed directly, not when imported ✓
  • C. It marks the function that Python calls first automatically
  • D. It prevents the module from being imported by other files
Correct answer: B. __name__ equals '__main__' only when the file is run directly, so the block is skipped when the module is imported elsewhere.
What will list(range(1, 10, 2)) produce?
  • A. [1, 3, 5, 7, 9] ✓
  • B. [1, 2, 3, ..., 9]
  • C. [2, 4, 6, 8]
  • D. [1, 3, 5, 7, 9, 11]
Correct answer: A. range(1, 10, 2) yields odd numbers from 1 up to but not including 10.
What does a list comprehension [x*x for x in range(3)] evaluate to?
  • A. [0, 1, 2]
  • B. [1, 4, 9]
  • C. [0, 1, 4] ✓
  • D. [0, 2, 4]
Correct answer: C. It squares 0, 1, and 2, giving [0, 1, 4].
What is the key difference between a shallow copy and a deep copy?
  • A. Shallow copy duplicates nested objects; deep copy does not
  • B. Deep copy duplicates nested objects recursively; shallow copy shares references to them ✓
  • C. They are identical in behavior
  • D. Shallow copy is only for tuples
Correct answer: B. A deep copy recursively copies nested objects, while a shallow copy copies the top level and shares inner references.
What happens when you use a mutable object as a default argument value in a function?
  • A. It raises a SyntaxError
  • B. A new object is created on every call
  • C. The same object persists across calls and can accumulate state ✓
  • D. Python converts it to an immutable version
Correct answer: C. Default arguments are evaluated once at definition, so a mutable default is shared and retains state across calls.
Which statement about Python generators is correct?
  • A. They compute and store all values in memory at once
  • B. They produce values lazily one at a time using yield ✓
  • C. They can only be iterated using a while loop
  • D. They cannot be used in for loops
Correct answer: B. Generators use yield to produce values lazily, keeping memory usage low.
What does the *args parameter allow a function to accept?
  • A. A variable number of keyword arguments
  • B. A variable number of positional arguments as a tuple ✓
  • C. Only two positional arguments
  • D. A dictionary of arguments
Correct answer: B. *args collects extra positional arguments into a tuple; **kwargs handles keyword arguments.
What is the output of bool('') and bool('0')?
  • A. True, True
  • B. False, False
  • C. False, True ✓
  • D. True, False
Correct answer: C. An empty string is falsy (False), but the non-empty string '0' is truthy (True).
Which context manager pattern ensures a file is closed even if an exception occurs?
  • A. Using open() without closing
  • B. Using with open(...) as f: ✓
  • C. Wrapping in try without finally
  • D. Calling f.close() at the top
Correct answer: B. The 'with' statement guarantees the file's __exit__ runs, closing it even on exceptions.
What does the enumerate() function provide when iterating a list?
  • A. Only the values
  • B. Only the indices
  • C. Pairs of (index, value) ✓
  • D. A reversed list
Correct answer: C. enumerate() yields (index, value) tuples, useful for tracking position while iterating.
What is the difference between == and is in Python?
  • A. == compares identity; is compares values
  • B. == compares values; is compares object identity ✓
  • C. They are interchangeable
  • D. is works only on numbers
Correct answer: B. == checks value equality, while is checks whether two references point to the same object.
What is printed by: def f(x, lst=[]): lst.append(x); return lst — after calling f(1) then f(2)?
  • A. [1] then [2]
  • B. [1] then [1, 2] ✓
  • C. [2] then [1, 2]
  • D. [1, 2] then [1, 2]
Correct answer: B. The mutable default argument persists across calls, so the second call appends to the same list.
Which statement about a Python generator is correct?
  • A. It stores all values in memory at once
  • B. It produces values lazily one at a time ✓
  • C. It is always reusable after exhaustion
  • D. It must return a list
Correct answer: B. Generators yield values lazily and are single-use iterators, saving memory.
What does the expression list(zip([1,2,3],[4,5])) return?
  • A. [(1,4),(2,5),(3,None)]
  • B. [(1,4),(2,5)] ✓
  • C. [(1,4),(2,5),(3,)]
  • D. Error
Correct answer: B. zip stops at the shortest iterable, so the third element of the first list is dropped.
In a list comprehension [x for x in range(10) if x % 2], which values are kept?
  • A. Even numbers
  • B. Odd numbers ✓
  • C. All numbers
  • D. Multiples of 2
Correct answer: B. x % 2 is truthy (1) for odd numbers, so only odd values pass the filter.
Which decorator turns a method into one callable on the class without an instance and without receiving the class?
  • A. @classmethod
  • B. @property
  • C. @staticmethod ✓
  • D. @abstractmethod
Correct answer: C. @staticmethod defines a method that receives neither self nor cls.
What does 'is' compare that '==' does not?
  • A. Value equality
  • B. Object identity ✓
  • C. String length
  • D. Type only
Correct answer: B. 'is' checks identity (same object), while '==' checks value equality.
What happens when you use a set to deduplicate the list [3, 1, 2, 1, 3]?
  • A. Order is guaranteed as [3,1,2]
  • B. Duplicates removed, insertion order not guaranteed ✓
  • C. Raises a TypeError
  • D. Returns [1,2,3] always sorted
Correct answer: B. Sets remove duplicates but do not preserve insertion order, so ordering is not guaranteed.
Which context manager guarantees a file is closed even if an exception occurs?
  • A. A plain open() call
  • B. A with statement ✓
  • C. A try without finally
  • D. A global open reference
Correct answer: B. The with statement ensures the file's __exit__ runs and closes it regardless of exceptions.
Which of these correctly merges two dicts a and b in Python 3.9+?
  • A. a + b
  • B. a | b ✓
  • C. a & b
  • D. merge(a, b)
Correct answer: B. The | operator merges dictionaries in Python 3.9+, with b's keys taking precedence.

Hard round 30 questions

You run this code: ```python def make_multipliers(): return [lambda x: i * x for i in range(4)] print([f(10) for f in make_multipliers()]) ``` What is printed, and why?
  • A. [0, 10, 20, 30] — each lambda captures its own copy of i at creation time
  • B. [30, 30, 30, 30] — all lambdas share i via late binding and see its final value 3 ✓
  • C. [0, 0, 0, 0] — i is reset to 0 when the list comprehension exits
  • D. TypeError — i is undefined inside the lambda scope
Correct answer: B. Closures capture the variable i by reference, not value, so all four lambdas read i's final value (3) when called, giving 3*10 four times.
A function accumulates data across calls: ```python def add_item(item, bucket=[]): bucket.append(item) return bucket print(add_item(1)) print(add_item(2)) ``` What is printed?
  • A. [1] then [2]
  • B. [1] then [1, 2] ✓
  • C. [1] then [2, 1]
  • D. [1, 2] then [1, 2]
Correct answer: B. The default list is created once at function-definition time and shared across every call that omits the argument, so it accumulates: [1] then [1, 2].
Your CPU-bound number-crunching function is slow, so you split it across 4 threads via threading.Thread on CPython 3.11. Wall-clock time barely improves (and sometimes worsens). What is the correct explanation and fix?
  • A. Threads block on I/O; switch to asyncio to overlap the waits
  • B. The GIL serializes bytecode execution so only one thread runs Python at a time; use multiprocessing to get true parallelism ✓
  • C. Thread creation overhead dominates; reuse a ThreadPoolExecutor and it will parallelize
  • D. The default recursion limit throttles threads; raise sys.setrecursionlimit and threads will scale
Correct answer: B. Under the GIL only one thread executes Python bytecode at a time, so CPU-bound work doesn't parallelize with threads; multiprocessing (separate interpreters/processes) sidesteps the GIL.
Consider: ```python a = 256 b = 256 c = 257 d = 257 print(a is b, c is d) ``` Run as a normal script (not line-by-line in a REPL). What is the most reliable output?
  • A. True True ✓
  • B. True False
  • C. False False
  • D. False True
Correct answer: A. CPython caches small integers from -5 to 256 so a is b is True; and because c and d are compiled in the same code block, the peephole/const-folding often interns 257 too, so both are True in a script.
You have this class hierarchy: ```python class A: def __init__(self): print('A'); super().__init__() class B(A): def __init__(self): print('B'); super().__init__() class C(A): def __init__(self): print('C'); super().__init__() class D(B, C): def __init__(self): print('D'); super().__init__() D() ``` What is printed?
  • A. D B A C A
  • B. D B A
  • C. D B C A ✓
  • D. D B C A C A
Correct answer: C. C3 linearization gives MRO D→B→C→A→object, and cooperative super() walks it exactly once each, so A prints only once after C: D B C A.
A colleague writes a data-only descriptor to validate an attribute but it seems ignored — reads return the instance-dict value directly. Which single fact explains when an instance __dict__ entry shadows a class-level descriptor?
  • A. Instance dict always wins over any class attribute, descriptor or not
  • B. A non-data descriptor (only __get__) is shadowed by an instance-dict entry, but a data descriptor (defines __set__ or __delete__) takes precedence ✓
  • C. Descriptors only work on classes using __slots__
  • D. Data descriptors are shadowed by the instance dict; non-data descriptors always win
Correct answer: B. Attribute lookup gives data descriptors (those defining __set__/__delete__) priority over the instance dict, while non-data descriptors are overridden by an instance-dict entry of the same name.
You must call a blocking, thread-unsafe legacy function `legacy_query()` from inside an async coroutine without freezing the event loop. Which approach is correct and safe?
  • A. await legacy_query() — awaiting any callable offloads it automatically
  • B. result = await asyncio.get_running_loop().run_in_executor(None, legacy_query) ✓
  • C. asyncio.create_task(legacy_query()) so it runs concurrently on the loop
  • D. Wrap it: result = await asyncio.wait_for(legacy_query(), timeout=5)
Correct answer: B. run_in_executor moves the blocking call onto a worker thread and returns an awaitable, so the event loop keeps running; awaiting a plain blocking function or wrapping a non-coroutine in create_task/wait_for is invalid or still blocks.
This Django view triggers a performance alarm: ```python for book in Book.objects.all(): print(book.author.name) # author is a ForeignKey ``` With 500 books, roughly how many DB queries run and what is the right fix?
  • A. 1 query; already optimal
  • B. 501 queries (N+1); fix with Book.objects.select_related('author') ✓
  • C. 501 queries (N+1); fix with Book.objects.prefetch_related('author')
  • D. 2 queries; fix with .only('author')
Correct answer: B. Each book.author triggers a separate query (1 + 500 = 501, the N+1 problem); select_related does a SQL JOIN for the forward ForeignKey in one query, whereas prefetch_related is for reverse/many-to-many relations.
Predict the output: ```python def gen(): try: yield 1 yield 2 finally: print('cleanup') g = gen() print(next(g)) g.close() print('done') ```
  • A. 1, then done (finally never runs because we didn't exhaust it)
  • B. 1, then cleanup, then done ✓
  • C. 1, then RuntimeError from close()
  • D. 1, then done, then cleanup
Correct answer: B. generator.close() raises GeneratorExit at the paused yield, which unwinds through the finally block (printing 'cleanup') before close() returns, then 'done' prints.
You need a shallow-vs-deep-copy-safe 3x3 grid initialized to zeros: ```python grid = [[0] * 3] * 3 grid[0][0] = 5 print(grid) ``` What is printed?
  • A. [[5, 0, 0], [0, 0, 0], [0, 0, 0]]
  • B. [[5, 0, 0], [5, 0, 0], [5, 0, 0]] ✓
  • C. [[5, 5, 5], [0, 0, 0], [0, 0, 0]]
  • D. [[5, 5, 5], [5, 5, 5], [5, 5, 5]]
Correct answer: B. The outer `* 3` replicates the same inner-list reference three times, so mutating grid[0][0] is visible through all three rows.
Why does the Global Interpreter Lock (GIL) limit CPython performance for CPU-bound multithreading?
  • A. It prevents any use of threads
  • B. It allows only one thread to execute Python bytecode at a time ✓
  • C. It disables multiprocessing entirely
  • D. It slows down all I/O operations
Correct answer: B. The GIL permits only one thread to run Python bytecode at once, so CPU-bound threads cannot truly run in parallel.
In Python's method resolution order (MRO), what algorithm does new-style class inheritance use?
  • A. Depth-first left-to-right
  • B. C3 linearization ✓
  • C. Breadth-first search
  • D. Random ordering
Correct answer: B. Python uses the C3 linearization algorithm to compute a consistent MRO for multiple inheritance.
What does applying @functools.wraps in a decorator accomplish?
  • A. It slows the wrapped function
  • B. It preserves the wrapped function's __name__ and __doc__ metadata ✓
  • C. It prevents the decorator from running
  • D. It makes the function immutable
Correct answer: B. functools.wraps copies metadata like __name__ and __doc__ from the original function onto the wrapper.
What is the primary reason dict lookups are O(1) on average in CPython?
  • A. Dicts store keys in a sorted array
  • B. Dicts use an open-addressing hash table ✓
  • C. Dicts use a balanced binary tree
  • D. Dicts perform linear scans with caching
Correct answer: B. CPython dicts use an open-addressing hash table, giving average O(1) key access.
In asyncio, what happens if you call a blocking synchronous function directly inside a coroutine?
  • A. It runs concurrently automatically
  • B. It blocks the entire event loop, stalling other tasks ✓
  • C. It raises a RuntimeError immediately
  • D. It is automatically offloaded to a thread
Correct answer: B. Blocking calls inside a coroutine freeze the single-threaded event loop, preventing other tasks from progressing.
What does __slots__ accomplish when defined on a class?
  • A. It makes all attributes read-only
  • B. It prevents inheritance
  • C. It restricts attributes and avoids a per-instance __dict__, saving memory ✓
  • D. It automatically adds getters and setters
Correct answer: C. __slots__ limits instances to declared attributes and omits __dict__, reducing memory overhead.
Why can a generator's state be resumed, unlike a regular function?
  • A. It stores its stack frame and instruction pointer between yields ✓
  • B. It restarts from the top each time
  • C. It copies its local variables to global scope
  • D. It uses a background thread
Correct answer: A. A generator suspends and preserves its frame (locals and position), allowing execution to resume after each yield.
What subtle bug can arise from late binding of closures in a loop, e.g., [lambda: i for i in range(3)]?
  • A. All lambdas return 0
  • B. All lambdas return the final value of i (2) ✓
  • C. It raises a NameError
  • D. Each lambda captures a distinct value
Correct answer: B. Closures capture the variable, not its value at creation, so all lambdas see i's final value of 2.
What does a metaclass control in Python?
  • A. The behavior of instances only
  • B. The creation and behavior of classes themselves ✓
  • C. Garbage collection timing
  • D. The import order of modules
Correct answer: B. A metaclass is the class of a class, controlling how classes are created and behave.
In CPython, why might sys.getrefcount() return a value higher than expected for an object?
  • A. Reference counting is disabled by default
  • B. Passing the object as an argument temporarily increments its refcount ✓
  • C. It counts weak references too
  • D. It always returns a random number
Correct answer: B. Passing the object to getrefcount() itself creates a temporary reference, inflating the reported count.
Why does the Global Interpreter Lock (GIL) limit CPU-bound multithreading in CPython?
  • A. It disables all threads entirely
  • B. Only one thread executes Python bytecode at a time ✓
  • C. It prevents I/O operations from running
  • D. It forces all threads onto one CPU core physically
Correct answer: B. The GIL allows only one thread to execute Python bytecode at once, serializing CPU-bound work.
What does the __slots__ attribute in a class primarily achieve?
  • A. Enables multiple inheritance
  • B. Prevents instance dict creation, reducing memory ✓
  • C. Makes attributes read-only
  • D. Speeds up method resolution order
Correct answer: B. __slots__ replaces the per-instance __dict__ with fixed storage, saving memory.
In CPython, what does functools.lru_cache use as the cache key by default?
  • A. Only positional arguments
  • B. The function's id
  • C. The arguments (positional and keyword) hashed ✓
  • D. The return value
Correct answer: C. lru_cache keys on the hashable call arguments, so all arguments must be hashable.
What is the method resolution order (MRO) algorithm used by Python for new-style classes?
  • A. Depth-first left-to-right
  • B. C3 linearization ✓
  • C. Breadth-first search
  • D. Alphabetical by class name
Correct answer: B. Python uses C3 linearization to compute a consistent MRO for multiple inheritance.
Which statement about asyncio is accurate?
  • A. It runs coroutines on multiple OS threads in parallel
  • B. A single event loop cooperatively schedules coroutines on one thread ✓
  • C. await blocks the entire process
  • D. Coroutines bypass the GIL for CPU work
Correct answer: B. asyncio uses a single-threaded event loop that cooperatively schedules coroutines at await points.
What does yield from in a generator accomplish?
  • A. Returns immediately ending the generator
  • B. Delegates iteration to a subgenerator, passing values and sends through ✓
  • C. Converts a generator to a list
  • D. Raises StopIteration early
Correct answer: B. yield from delegates to a subgenerator, transparently forwarding yielded values, sends, and returns.
Why can modifying a list while iterating over it with a for loop cause skipped elements?
  • A. The list is copied each iteration
  • B. The internal index advances while indices shift after deletion ✓
  • C. Iteration is random-order
  • D. Lists cannot be mutated at all
Correct answer: B. Removing an element shifts subsequent items left while the iterator's index still advances, skipping one.
What distinguishes __new__ from __init__ in object creation?
  • A. __init__ creates the instance; __new__ initializes it
  • B. __new__ creates/returns the instance; __init__ initializes it ✓
  • C. They are aliases
  • D. __new__ runs only for subclasses
Correct answer: B. __new__ allocates and returns the new instance, then __init__ initializes that instance.
When would a weakref.WeakValueDictionary be preferable to a normal dict for caching?
  • A. To keep cached objects alive forever
  • B. To allow cached values to be garbage-collected when no other references exist ✓
  • C. To make keys immutable
  • D. To speed up hashing
Correct answer: B. WeakValueDictionary holds weak references so entries vanish once no strong references remain, preventing leaks.
What is the effect of defining __hash__ = None on a class?
  • A. It makes instances hashable with id
  • B. It makes instances unhashable, so they can't be dict keys ✓
  • C. It caches the hash value
  • D. It raises at class definition time
Correct answer: B. Setting __hash__ to None makes instances unhashable, preventing their use as set members or dict keys.

Prep for another role

Questions are original, written and independently verified for HireHire's role interview quizzes. They reflect the kind of knowledge Python Developer interviews test, not any specific company's questions. HireHire maps live tech & IT jobs across India, updated regularly. Last updated: August 2026.