Skip to content
tezvyn:
Menu

Top 30 Python Interview Questions and Answers

30 multiple-choice questions on Python, drawn from 30 bites out of the 219 tagged Python on Tezvyn. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.

30 questions. Pick an answer, or open “Show the answer” to read it.

Answers are graded in your browser. Quiz progress is not saved, and no XP or streak is earned here. The app keeps score.

  1. Question 1 of 30

    Which scenario best highlights the primary benefit of using a pandas DataFrame?

    Show the answer

    Answer: a · Efficiently analyzing a large CSV file containing sales figures.

    The card states that DataFrames are the 'workhorse for loading, cleaning, and analyzing tabular data in Python, like sales figures from a CSV,' highlighting their efficiency for such tasks. DataFrames are not suitable for data too large for memory, deeply nested JSON, or simple single-column lists.

    Read the full bite: pandas DataFrame: A Spreadsheet in Code

  2. Question 2 of 30

    When converting a large list of flat dictionaries to a pandas DataFrame, which method is the idiomatic one-shot approach for aligning keys and avoiding repeated DataFrame growth?

    Show the answer

    Answer: c · Pass the list of dicts directly to pd.DataFrame so the constructor aligns the dictionary keys in one operation

    Passing the list directly to pd.DataFrame is the idiomatic approach for flat row-oriented dictionaries: it aligns the union of keys and fills missing values with NaN. Repeatedly growing a DataFrame can cause unnecessary copying, while the exact performance of alternatives depends on the data and pandas version.

    Read the full bite: Most efficient way to convert list of dicts to pandas DataFrame

  3. Question 3 of 30

    Which statement accurately describes a common behavior when slicing a NumPy ndarray?

    Show the answer

    Answer: b · Modifying elements in the sliced portion will also alter the original array if the slice is a view.

    The card explicitly states that 'slicing often creates a view, not a copy, so edits can alter the original.' This behavior is a feature for performance but a common source of bugs. Option A is a common misconception, as slicing does not always create a copy; it often creates a view.

    Read the full bite: NumPy ndarray: Fast, Typed, Multidimensional Grids

  4. Question 4 of 30

    For a DataFrame with a string index, which call raises an error and why?

    Show the answer

    Answer: d · df.iloc['x'], because iloc requires integer positions not labels

    iloc is strictly positional and rejects a string label, raising a TypeError. df.loc['x'] and df.iloc[0] both work correctly on a string-indexed frame.

    Read the full bite: Pandas loc versus iloc indexing

  5. Question 5 of 30

    Which approach correctly handles the full response lifecycle when fetching JSON from a REST API in production using Python's requests?

    Show the answer

    Answer: c · Verify the status with r.raise_for_status() before parsing with r.json()

    Calling r.raise_for_status() before trusting r.json() raises an HTTPError for unsuccessful responses before application code treats their bodies as successful payloads. r.json() parses the response body independently and can also raise a JSON decoding error when the body is not valid JSON; timeouts and connection errors need separate handling.

    Read the full bite: How do you fetch JSON from a REST API and parse it?

  6. Question 6 of 30

    When you annotate a FastAPI route parameter with a Pydantic model, what does the framework do with that type hint?

    Show the answer

    Answer: a · It leverages the hint for automatic request validation and OpenAPI schema generation

    FastAPI reads type hints at startup to construct Pydantic models that validate incoming requests and generate OpenAPI schemas automatically. The distractor about runtime enforcement is wrong because Python itself ignores type hints during execution unless an external tool checks them.

    Read the full bite: Explain Python type hints and their importance in FastAPI

  7. Question 7 of 30

    What is the primary mechanism by which Python type hints improve code reliability?

    Show the answer

    Answer: c · They enable static analysis tools to identify potential type mismatches before execution.

    Type hints are ignored by the Python interpreter at runtime. Their primary role is to allow static analysis tools to check for type consistency and potential errors before the code is ever executed, improving reliability. They do not perform runtime validation of external data.

    Read the full bite: Python Type Hints: Documentation Your Linter Can Read

  8. Question 8 of 30

    When should you import an agent framework like CrewAI or LangGraph instead of building a plain Python workflow?

    Show the answer

    Answer: b · Only when the orchestration complexity genuinely demands dynamic planning beyond explicit control flow

    The card argues that agent frameworks should be an upgrade, not a starting point, and adopted only when orchestration complexity truly requires dynamic planning. Option C describes when to use plain Python, while D inverts the card's warning that letting the LLM own the execution graph inherits hallucinations rather than eliminating them.

    Read the full bite: Most LLM Apps Need Workflows Not Agent Frameworks

  9. Question 9 of 30

    You write an async def FastAPI endpoint that calls requests.get. What is the main risk?

    Show the answer

    Answer: c · The event loop is blocked, freezing concurrent request handling until the call finishes.

    The correct answer is C because calling a blocking library like requests inside async def stalls the event loop, stopping all other requests. The most tempting distractor is A because beginners often assume FastAPI magically threadpools any blocking code, but only def endpoints are run in a threadpool.

    Read the full bite: What is the difference between def and async def in Python and FastAPI?

  10. Question 10 of 30

    For which scenario would a Python dataclass be the most suitable choice?

    Show the answer

    Answer: d · Creating a simple data structure to represent an API response with predefined fields.

    Dataclasses are designed for classes whose primary purpose is to store and group data, making them perfect for structured records like API responses. They are not recommended for classes with complex logic, intricate state, or custom initialization needs, which are better handled by regular classes.

    Read the full bite: Python Data Classes: Write Less Boilerplate

  11. Question 11 of 30

    What mechanism triggers FastAPI to automatically validate and parse an incoming JSON request body against a schema?

    Show the answer

    Answer: b · Using a Pydantic model as the type hint for a route parameter

    FastAPI inspects function signature type hints at runtime, so using a Pydantic model as a parameter type hint automatically triggers request parsing and validation. Manually calling json.loads inside the route is a red flag that ignores this declarative mechanism, and response_model governs response serialization, not request validation.

    Read the full bite: How does FastAPI leverage Pydantic for request validation and serialization?

  12. Question 12 of 30

    What is the primary function of an __init__.py file in a Python directory?

    Show the answer

    Answer: c · To explicitly designate the directory as a Python package.

    For a regular package, __init__.py historically marks the package and can run initialization code, so C is the intended answer in this question. Namespace packages can omit the file; importing submodules or exposing a public API is optional behavior, not automatic.

    Read the full bite: Python Packages: Grouping Modules with __init__.py

  13. Question 13 of 30

    When building an async execution-time decorator for FastAPI, why is omitting functools.wraps on the inner wrapper considered a red flag?

    Show the answer

    Answer: b · It strips the original function's metadata, which breaks FastAPI's OpenAPI schema generation and dependency injection.

    functools.wraps preserves the original function's name, signature, and metadata, which FastAPI relies on to generate OpenAPI docs and resolve dependencies; omitting it exposes the wrapper's metadata instead. Distractor A is wrong because wraps has no effect on whether code runs synchronously or blocks the event loop.

    Read the full bite: Write an async decorator that logs execution time for FastAPI

  14. Question 14 of 30

    What primary problem do Python Enums address in code?

    Show the answer

    Answer: c · Making code more readable and less prone to errors when using fixed sets of values.

    The card states Enums solve the problem of "magic values" by providing a "robust, readable, and type-safe way to define a fixed set of named constants," making code's intent "immediately clear." While Enums contribute to type safety, their primary purpose is to replace obscure "magic numbers" with meaningful names for fixed sets of choices, improving readability and reducing errors from typos or misunderstandings.

    Read the full bite: Python Enums: Give Names to Magic Numbers

  15. Question 15 of 30

    Which implementation correctly minimizes total latency when a FastAPI endpoint must fetch data from two independent external APIs?

    Show the answer

    Answer: a · Inside an async def endpoint, pass two httpx.AsyncClient coroutines to asyncio.gather and await the result.

    asyncio.gather with an async HTTP client schedules both I/O-bound coroutines concurrently on the event loop, reducing total latency to roughly the slower call. Option C is tempting because it uses async/await correctly, but sequential awaiting means the second request cannot start until the first finishes, so latencies add up.

    Read the full bite: How do you structure concurrent API calls with asyncio.gather in FastAPI?

  16. Question 16 of 30

    When a decorator is applied to a function, what is the immediate effect on that function's definition?

    Show the answer

    Answer: d · It replaces the original function in its scope with a new, wrapped function.

    The card states that the decorator returns a wrapper function, which 'replaces the original my_func in the surrounding scope.' This means the original function's name now refers to the new, wrapped function. Option A is incorrect because decorators add behavior without altering the original function's source code.

    Read the full bite: Python Decorators: Functions that Wrap Functions

  17. Question 17 of 30

    When a FastAPI endpoint awaiting asyncpg is suspended during a database query, how can Uvicorn process another incoming connection in the same worker process?

    Show the answer

    Answer: d · The event loop yields the coroutine at the await, registers the socket with epoll or kqueue, and schedules the new connection's coroutine on the same thread.

    The correct answer describes cooperative multitasking: the event loop suspends the coroutine at await and interleaves I/O-bound tasks on a single thread. Distractor A is wrong because Uvicorn does not use multiple Python threads to handle requests; concurrency comes from the loop scheduling coroutines, not from threading or GIL behavior.

    Read the full bite: How does Uvicorn use asyncio to handle thousands of concurrent connections?

  18. Question 18 of 30

    What is the primary benefit of using `yield` in a Python function?

    Show the answer

    Answer: a · It enables the function to pause and resume execution, producing values on-demand to conserve memory.

    The card states generators process data lazily, yielding one item at a time to conserve memory by pausing and resuming execution. Option D is incorrect because generators are one-time-use iterators.

    Read the full bite: Python's `yield`: Functions That Pause and Resume

  19. Question 19 of 30

    In FastAPI, why should an async database session dependency wrap yield in try and place await session.close() in finally?

    Show the answer

    Answer: a · It guarantees cleanup runs even if the path operation raises an exception.

    A try/finally block guarantees that await session.close() runs even when the path operation raises an exception, preventing database connection leaks. The thread pool issue in distractor C is caused by using def instead of async def, not by omitting exception handling.

    Read the full bite: Implement an async database session dependency using yield for setup and teardown

  20. Question 20 of 30

    What is the primary advantage of using a `with` statement in Python for resource management?

    Show the answer

    Answer: d · It ensures that acquired resources are reliably released, regardless of execution flow or errors.

    The `with` statement's core benefit is guaranteeing that resources like file handles or network connections are properly closed or released, even if exceptions interrupt the program flow. While it interacts with errors, it doesn't automatically handle all exceptions; rather, it ensures cleanup *despite* them.

    Read the full bite: The `with` Statement: Python's Automatic Cleanup Crew

  21. Question 21 of 30

    What is the immediate result of calling a function defined with async def, like my_coro(), without awaiting it?

    Show the answer

    Answer: c · A coroutine object is returned, which must be explicitly run by an event loop.

    Calling an async def function directly only creates a coroutine object; it does not execute the function's code. This object must then be awaited or scheduled with an event loop to run. Option B describes synchronous function behavior, and Option A incorrectly implies immediate background execution without the necessary explicit step.

    Read the full bite: Python Coroutines: Functions You Can Pause and Resume

  22. Question 22 of 30

    When an incoming GET request reaches a FastAPI app, how does @app.get("/") enable the correct function to run?

    Show the answer

    Answer: d · It registers the function in the app's route table at import time and generates OpenAPI metadata.

    The decorator actively registers the function for GET / in the app's internal route table when the module is imported and simultaneously populates the OpenAPI schema, enabling the ASGI layer to dispatch matching requests. Calling it pure syntax sugar is a common misconception because it fundamentally alters the application's routing registry and automatic documentation rather than leaving framework behavior unchanged.

    Read the full bite: What is the purpose of @app.get("/") in FastAPI?

  23. Question 23 of 30

    For which scenario would Python's async/await typically NOT provide a performance benefit?

    Show the answer

    Answer: b · Processing a large dataset with intensive numerical calculations.

    Async/await is designed for I/O-bound tasks where the program spends time waiting, allowing other tasks to run during these waits. CPU-bound tasks, like intensive numerical calculations, will block the single event loop, preventing any other tasks from progressing and thus negating the benefits of concurrency.

    Read the full bite: Python's async/await: Concurrent, Not Parallel

  24. Question 24 of 30

    Which approach correctly defines a FastAPI endpoint that captures an integer item_id from a URL like /items/42?

    Show the answer

    Answer: a · Use app.get("/items/{item_id}") and define async def read_item(item_id: int): then use item_id directly inside the function

    FastAPI binds curly-braced path segments to function arguments with matching names and type hints, automatically converting and injecting the value. Option B is tempting because the route syntax is correct, but the mismatched argument name breaks the default binding unless you use a Path alias.

    Read the full bite: How do you define and access a FastAPI path parameter?

  25. Question 25 of 30

    You write an async generator that awaits during resource teardown, but mistakenly decorate it with @contextmanager. What is the most likely result?

    Show the answer

    Answer: b · A runtime error occurs because the synchronous decorator cannot await inside the generator

    The card explicitly warns that @contextmanager is for synchronous generators only and cannot await, causing a crash. Distractor A is tempting because blocking the event loop is discussed as a general risk of async code, but the specific mistake of using the sync decorator with async cleanup results in a runtime error rather than silent blocking.

    Read the full bite: Python Async Context Managers

  26. Question 26 of 30

    Which FastAPI endpoint declaration identifies a user in the URL path and accepts an optional search term after the question mark?

    Show the answer

    Answer: a · Route /users/{user_id}/items with user_id in path and q optional

    Option A correctly places the user identifier in the path template and gives q a default of None so it becomes an optional query parameter. Option B is tempting because it also makes q optional, but it omits user_id from the path so FastAPI treats it as a query parameter, violating RESTful hierarchy.

    Read the full bite: What is the difference between a path parameter and a query parameter?

  27. Question 27 of 30

    What specific problem did direct access to "__annotations__" for a class, like "Derived.__annotations__", commonly cause in Python 3.9 that "inspect.get_annotations()" addresses in Python 3.10+?

    Show the answer

    Answer: c · It would incorrectly show annotations inherited from a parent class, even if the derived class had no explicit annotations.

    In Python 3.9 and earlier, direct access to a class's __annotations__ would incorrectly include annotations inherited from parent classes. Python 3.10+ and `inspect.get_annotations()` resolve this by ensuring a class's __annotations__ only contains its own explicitly defined annotations, returning an empty dictionary if none are present.

    Read the full bite: Accessing Python Type Annotations Safely

  28. Question 28 of 30

    An endpoint declares a query parameter as q: Optional[str] with no default value. What happens when a client omits it?

    Show the answer

    Answer: c · FastAPI returns a 422 Unprocessable Entity error

    FastAPI derives requirement from the presence or absence of a Python signature default, not from type hints, so Optional[str] without = None is still required and omitting it triggers a 422 error. Option D is a common misconception because Optional alone does not make a parameter optional in FastAPI.

    Read the full bite: How does FastAPI distinguish required optional and default query parameters

  29. Question 29 of 30

    Why is Python's threading module generally not recommended for speeding up CPU-bound tasks on multi-core machines?

    Show the answer

    Answer: a · The Global Interpreter Lock (GIL) prevents multiple threads from executing Python bytecode simultaneously.

    The card states that the GIL "prevents multiple threads from executing Python code at the same time," which is the fundamental reason threading cannot achieve true parallelism for CPU-bound tasks. While thread management overhead (option C) can make a program slower, the GIL is the core reason it won't speed up by utilizing multiple CPU cores.

    Read the full bite: Python Concurrency vs. Parallelism

  30. Question 30 of 30

    What combination of standard and code sources enables FastAPI's automatic interactive documentation?

    Show the answer

    Answer: d · It dynamically builds an OpenAPI schema from type hints, Pydantic models, decorators, and docstrings

    FastAPI dynamically generates an OpenAPI schema by extracting metadata from type hints, Pydantic models, decorators, and docstrings, so no manual schema file is required. Option B is wrong because maintaining a separate openapi.yaml by hand is unnecessary and contradicts FastAPI's design.

    Read the full bite: What standard and code elements power FastAPI's auto-generated API docs?

Could you explain these out loud?

That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon