Python interview questions in 2026 test four things: core language fundamentals (data types, functions, OOP, error handling), hands-on coding, data manipulation with libraries like pandas, and, increasingly, how you use Python to build with LLMs and AI agents.
How deep each area goes depends on your level: freshers are still asked about lists vs tuples and mutability, while experienced candidates are now also expected to discuss async code, type hints, Pydantic, LLM API calls, tool calling, and agent evaluation. This guide covers all of it, grouped by level and role, with answers you can say out loud in an interview.
That last area is new. When this guide was first published in 2021, a Python interview for a data role meant syntax, pandas, and a few plots. Those topics are still the base, but the jobs built on them have changed: data scientists now ship LLM features, data engineers feed retrieval pipelines, and teams hire AI engineers and agent developers who use Python to connect models, tools, and data.
To reflect those roles, we have rebuilt the question bank. The fundamentals are still here, corrected and updated for current Python 3, and new sections now cover data engineering, LLM and AI engineering, agentic AI, and scripting.
How this guide is organized:
Python Basic Interview Questions (freshers)
Python Programming Interview Questions(intermediate concepts)
Python Coding Interview Questions (with code)
Pandas and Data Manipulation Questions
Python Interview Questions for Experienced Developers
Python Interview Questions for Data Engineers
Python Interview Questions for LLM and AI Engineering Roles
Agentic AI Python Interview Questions
Python Scripting Interview Questions
A Python Interview Preparation Plan
How Python Interviews Have Changed with Agentic AI
The biggest change is in what interviewers choose to test. Since they now assume you can use an AI coding assistant, they focus on what the assistant cannot do for you: reading code critically, designing reliable systems, and debugging when things fail. As a result, rote syntax questions carry less weight while reasoning about trade-offs carries more, as the comparison below shows.
What interviews tested earlier | What Python interviews test now |
|---|---|
Syntax recall (list methods, string functions) | Reading, reviewing and fixing code, including AI-generated code |
pandas and plotting | pandas plus SQL, Polars, data validation and pipeline design |
Scripts that run once | Production code: type hints, tests, packaging, logging |
Synchronous code | async/await for concurrent API and I/O calls |
Training ML models | Calling LLM APIs, structured outputs, embeddings and RAG |
Tool calling, agent loops, MCP, guardrails and agent evaluation |
In the interview room, this change shows up in three practical ways:
Live coding with AI allowed (or explicitly banned): Some companies let you use an assistant and then grill you on every line. Others ban it and test fundamentals harder. Prepare for both.
Code review rounds: You get a buggy or slow Python function and must explain what is wrong. Mutable default arguments, shallow copies, and unhandled exceptions are favorites.
System design for AI features: Even mid-level roles may ask how you would build a Python service that calls an LLM, validates its output, and retries safely.
Python Interview Topics by Role
These shifts do not affect every role equally. The core Python interview topics are the same for everyone; what changes is how deep each one goes and which extra topics are added. Use this table to decide which sections of this guide to focus on.
Role | Core Python topics | Role-specific topics | Sections to prioritize |
|---|---|---|---|
Fresher / Python developer | Data types, control flow, functions, OOP, exceptions | Basic algorithms, string and list problems | Basics, programming, coding |
Data analyst/data scientist | Comprehensions, functions, OOP basics | pandas, NumPy, visualization, statistics | Basics, coding, pandas |
Data engineer | Generators, file handling, error handling | Chunked processing, PySpark, Polars, Airflow, data validation | Coding, data engineering, scripting |
Experienced Python developer | Memory model, GIL, decorators, context managers | async, typing, testing, packaging, performance | Programming, experienced |
AI / ML engineer | All of the above | LLM APIs, Pydantic, embeddings, RAG, async | Experienced, AI engineering |
Agentic AI developer | All of the above | Tool calling, agent loops, MCP, memory, guardrails, evals | AI engineering, agentic AI |
Python Basic Interview Questions (For Freshers)
Whichever row of that table describes you, the first round almost always starts with these Python basic interview questions. Interviewers use them to check fundamentals quickly, so answer each one crisply and add a small example.

Q1. What is Python, and why is it so widely used?
Python is a high-level, interpreted, dynamically typed, general-purpose language. It is popular because it is readable, has a huge ecosystem (pandas, NumPy, scikit-learn, PyTorch, FastAPI), and is the default language for data science, automation, and AI development, including most LLM and agent frameworks.
Q2. Is Python object-oriented? What is object-oriented programming?
Yes. Everything in Python is an object, and it supports classes, inheritance, encapsulation, and polymorphism. OOP bundles data (attributes) and behavior (methods) into objects. Python is multi-paradigm, so you can also write procedural and functional code.
Q3. What is the difference between a module, a package and a library?
A module is a single .py file. A package is a directory of modules (traditionally with an __init__.py). A library is a loose term for a collection of packages that provides reusable functionality, such as pandas or requests.
Q4. What is PEP 8?
PEP 8 is Python's official style guide. It covers naming, indentation (4 spaces), line length, and import order. In practice, teams enforce it with tools like Ruff or Black rather than by hand.
Q5. Which Python objects are mutable and which are immutable?
Mutable (can change in place):
list,dict,set,bytearray, most user-defined objects.Immutable:
int,float,bool,str,tuple,frozenset,bytes.
The distinction matters most for dictionaries, because keys must be hashable, which in practice means immutable.
Q6. What is the difference between a list and a tuple?
List | Tuple |
|---|---|
Square brackets: | Parentheses: |
Mutable | Immutable |
Not hashable, cannot be a dict key | Hashable if its elements are, so it can be a dict key |
Slightly more memory | Slightly less memory, a little faster to create |
Use for collections that change | Use for fixed records, such as coordinates or function returns |
One thing the table doesn't separate is order: both preserve it, so order alone is never a reason to choose one over the other.
Q7. What are list, dict and set comprehensions?
Comprehensions build a collection from an iterable in one readable expression.
squares = [n * n for n in range(10) if n % 2 == 0] # [0, 4, 16, 36, 64]
prices = {item: price for item, price in zip(["a", "b"], [10, 20])}
unique_lengths = {len(word) for word in ["ai", "agent", "llm"]}Comprehensions are best kept short; once you need nested conditions, a regular loop is easier to read.
Q8. What is the difference between is and ==?
== checks whether two values are equal. is checks whether two names point to the same object in memory. Use is only for singletons such as None: if result is None:.
Q9. What is the difference between /, // and %?
/ is true division and always returns a float (11 / 2 is 5.5). // is floor division (11 // 2 is 5; -11 // 2 is -6). % returns the remainder (11 % 2 is 1).
Q10. What is a lambda function?
A lambda is a small anonymous function with a single expression.
add = lambda a, b: a + b
sorted_users = sorted(users, key=lambda u: u["age"])Like any function, a lambda can read variables from enclosing scopes; its only limit is that the body must be a single expression. That limit is why lambdas suit short sort keys and callbacks, while def is better for anything you need to name, test, or document.
Q11. What do *args and **kwargs mean?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict. They are common in wrappers and decorators that pass arguments through to another function.
def log_call(*args, **kwargs):
print(args, kwargs)
log_call(1, 2, model="small") # (1, 2) {'model': 'small'}Q12. How does exception handling work in Python?
Use try for code that may fail, except for specific errors, else for code that runs only if no error occurred, and finally for cleanup that always runs.
try:
value = int(user_input)
except ValueError:
value = 0
else:
print("Parsed")
finally:
print("Done")Always catch specific exceptions, because a bare except: also swallows bugs you did not expect, and even keyboard interrupts.
Additionally, read our detailed guide with working examples - Exceptional Handling in Python.
Q13. What is the difference between pass, continue and break?
pass does nothing and acts as a placeholder. continue skips to the next loop iteration. break exits the innermost loop immediately.
Q14. What do zip() and enumerate() do?
zip() pairs items from several iterables and stops at the shortest one. enumerate() yields (index, item) pairs. In Python 3, both return lazy iterators, so wrap them in list() to see the values.
list(zip(["a", "b"], [1, 2])) # [('a', 1), ('b', 2)]
list(enumerate(["x", "y"], start=1)) # [(1, 'x'), (2, 'y')]Q15. What is the difference between remove(), pop(), del and clear() on a list?
remove(x) deletes the first item equal to x. pop(i) removes and returns the item at index i (the last one by default). del lst[i] deletes by index or slice and returns nothing. clear() empties the list.
Python Programming Interview Questions (Intermediate Concepts)
Once the basics are covered, interviewers move on to how Python behaves under the hood. These Python programming interview questions separate candidates who have written real code from those who have only read tutorials, so expect a follow-up on each.

Q16. What is the difference between an iterator and a generator?
An iterator is any object with __iter__() and __next__(). A generator is an easy way to create one: a function that uses yield. Generators produce values lazily, one at a time, so they use very little memory.
def read_large_file(path):
with open(path) as f:
for line in f:
yield line.strip()This pattern lets you process a 10 GB log file without loading it into memory, and it is the same idea used to stream LLM responses token by token.
Q17. What is a decorator? Write a simple one.
A decorator is a function that takes a function and returns a modified version of it, without changing its source code. Common uses are logging, timing, caching, retries, and access checks.
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapperfunctools.wraps keeps the original function's name and docstring, which matters because other tools read them. Agent frameworks are a good example: many use a decorator to register a Python function as a tool, and that docstring becomes the description the model reads (see Q63).
Q18. What is the mutable default argument trap?
Default arguments are evaluated once, when the function is defined, not on every call.
def add_item(item, items=[]): # bug
items.append(item)
return items
add_item(1) # [1]
add_item(2) # [1, 2] (same list reused)The fix is items=None, then if items is None: items = [] inside the function. This is one of the most common code-review interview questions.
Q19. What is the difference between a shallow copy and a deep copy?
A shallow copy (copy.copy(), list.copy(), slicing) creates a new outer object but shares the nested objects. A deep copy (copy.deepcopy()) recursively copies everything. If you shallow-copy a list of dicts and edit a dict, the original changes too.
Q20. What is the GIL, and does it still matter?
The Global Interpreter Lock allows only one thread to execute Python bytecode at a time in the standard CPython build. So threads help with I/O-bound work (network calls, file reads) but not CPU-bound work, where you use multiprocessing or libraries like NumPy that release the GIL.
This limit is changing, which is worth mentioning in a 2026 interview: Python 3.13 introduced an experimental free-threaded build without the GIL (PEP 703), and Python 3.14 made it officially supported, though the standard build still has the GIL by default.
Q21. How does Python manage memory?
CPython uses reference counting: each object tracks how many references point to it and is freed when the count hits zero. A cyclic garbage collector (the gc module) cleans up reference cycles that counting alone cannot free. Small integers and some strings are cached and reused.
Q22. Explain the LEGB rule and the global and nonlocal keywords.
Python resolves names in this order: Local, Enclosing function, Global (module), Built-in. global x lets a function assign to a module-level variable. nonlocal x lets a nested function assign to a variable in its enclosing function, which is how closures keep state.
Q23. What is a context manager?
A context manager sets something up and guarantees cleanup, even if an error occurs. You use it with with. Files, database connections, locks, and HTTP clients are typical examples.
from contextlib import contextmanager
@contextmanager
def db_session():
conn = connect()
try:
yield conn
finally:
conn.close()The decorator above is a shortcut; the longer equivalent is a class that implements __enter__ and __exit__.
Q24. What is the difference between @staticmethod, @classmethod and an instance method?
An instance method receives self and works on one object. A @classmethod receives cls and is often used for alternative constructors, such as User.from_dict(data). A @staticmethod receives neither; it is a plain function grouped inside the class for organization.
Q25. What are dataclasses, and when would you use them?
@dataclass auto-generates __init__, __repr__ and __eq__ for classes that mainly hold data. That makes it ideal for simple records. Dataclasses do not check types at runtime, however, so when you need to validate external data, such as API payloads or LLM outputs, most teams use Pydantic models instead (see Q56).
Python Coding Interview Questions (With Code)
Explaining a concept is only half the test, because the next round asks you to apply it. Python coding interview questions check whether you can turn a problem into clean, efficient code and explain its time complexity, so say your approach before you type and state the Big-O at the end.

Q26. Check whether a string is a palindrome, ignoring case and punctuation.
def is_palindrome(text: str) -> bool:
cleaned = [c.lower() for c in text if c.isalnum()]
return cleaned == cleaned[::-1]
is_palindrome("A man, a plan, a canal: Panama") # TrueThis runs in O(n) time and O(n) space, because it builds a cleaned copy of the string. A two-pointer version skips the copy and brings space down to O(1).
Q27. Two Sum: return the indices of two numbers that add up to a target.
def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = i
return NoneA dictionary gives O(n) time instead of the O(n²) nested-loop solution. Interviewers want to hear that trade-off.
Q28. Find the k most frequent words in a text.
from collections import Counter
def top_k_words(text: str, k: int) -> list[tuple[str, int]]:
words = text.lower().split()
return Counter(words).most_common(k)Using a built-in here instead of a hand-written counting loop is deliberate, because knowing the collections module (Counter, defaultdict, deque) is a quick signal of Python fluency.
Q29. Flatten an arbitrarily nested list.
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]Because it is a generator, this version handles large inputs lazily. Its weak spot is recursion, since very deep nesting can hit Python's recursion limit, so mention that trade-off.
Q30. Group a list of words into anagrams.
from collections import defaultdict
def group_anagrams(words: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())Q31. Write a fast Fibonacci function.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)Without caching, recursion recalculates the same values repeatedly and takes exponential time; memoization stores each result once, bringing it down to O(n). An iterative loop with two variables is O(n) time and O(1) space, and avoids recursion limits.
Q32. Find the first non-repeating character in a string.
from collections import Counter
def first_unique(s: str) -> str | None:
counts = Counter(s)
return next((c for c in s if counts[c] == 1), None)Q33. Code review: what does this print, and how do you fix it?
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])It prints [2, 2, 2], not [0, 1, 2]. Closures capture the variable i, not its value at creation time (late binding). Fix it by binding the value as a default argument: lambda i=i: i. This style of "spot the bug" question is now common because candidates are expected to review AI-generated code, not just write code.
Pandas and Data Manipulation Interview Questions
For data roles, the coding round usually moves from plain Python to pandas, often as small live tasks on a sample DataFrame. Interviewers check two things here: whether you know the syntax, and whether you know when pandas is the wrong tool (Q40).

Q34. What is the difference between .loc and .iloc?
.loc selects by label and includes the end of a slice. .iloc selects by integer position and excludes the end, like Python's range.
df.loc[0:3, ["name", "sales"]] # rows labelled 0 to 3 (4 rows if the index is 0, 1, 2...)
df.iloc[0:3, 0:2] # first 3 rows, first 2 columnsQ35. What is the difference between merge(), join() and concat()?
Method | Joins on | Default | Typical use |
|---|---|---|---|
| Columns (or index) | Inner join | SQL-style joins |
| Index | Left join | Quick joins on an index |
| Stacks along an axis | Rows ( | Appending datasets with the same columns |
A common slip in live tasks: concat takes a list of DataFrames.
Q36. How do you use groupby with multiple aggregations?
Use named aggregation, which calculates several metrics in one pass and names each output column clearly:
summary = (
df.groupby("region")
.agg(total_sales=("sales", "sum"),
avg_order=("order_value", "mean"),
customers=("customer_id", "nunique"))
.reset_index()
)Q37. Why should you avoid apply() when you can vectorize?
apply() runs a Python function row by row, which is slow on large data. Vectorized operations run in optimized C code.
# Slow
df["total"] = df.apply(lambda r: r["price"] * r["qty"], axis=1)
# Fast
df["total"] = df["price"] * df["qty"]The same principle applies to conditional logic: use np.where() or np.select() instead of apply().
Q38. How do you handle missing values?
Find them with df.isna().sum(). Then drop (dropna()), fill (fillna() with a constant, mean, median, or forward-fill), or interpolate. The right choice depends on why the data is missing. A strong answer explains that choice rather than reaching for fillna(0) by default.
Q39. What changed in pandas 3.0 that you should know for interviews?
pandas 3.0, released in January 2026, made two big changes to the defaults. First, Copy-on-Write: any result of indexing now behaves like a copy, so chained assignment such as df[df.x > 0]["y"] = 1 no longer modifies df, and the old SettingWithCopyWarning is gone. Use df.loc[df.x > 0, "y"] = 1 instead. Second, string columns now get a dedicated str dtype instead of object.
Q40. When would you use Polars or DuckDB instead of pandas?
The limit comes from how pandas works: it loads all data into memory and mostly runs on a single core. For datasets of tens of gigabytes, Polars (a multi-threaded DataFrame library with lazy evaluation) or DuckDB (an in-process SQL engine that queries Parquet and CSV files directly) are often much faster. For distributed data beyond one machine, use PySpark. Interviewers like candidates who pick tools by data size, not habit.
Q41. Which Python libraries have you used for data visualization, and when?
Matplotlib is the low-level base for full control. Seaborn builds on it for quick statistical plots (distributions, box plots, heatmaps, pair plots). Plotly creates interactive charts for dashboards and notebooks. A good answer explains when to use each, for example, Seaborn for exploration and Plotly for a stakeholder-facing dashboard.
Python Interview Questions for Experienced Developers
For experienced candidates (3+ years), the question shifts from whether you know Python's features to whether your code survives production. Python interview questions at this level therefore focus on concurrency, reliability, testing, and maintainability, and the strongest answers include a real example from your own work.

Q42. When do you use threading, multiprocessing, or asyncio?
Approach | Best for | Why |
|---|---|---|
| I/O-bound work with blocking libraries | Threads wait on I/O in parallel; the GIL limits CPU work |
| CPU-bound work (heavy computation) | Separate processes, each with its own interpreter and GIL |
| Many concurrent I/O tasks (API calls, web requests) | One thread, cooperative switching, very low overhead per task |
Applied to a common case, an AI app that calls an LLM API 500 times spends most of its time waiting on the network, so asyncio is usually the right answer, as the next question shows.
Q43. Write code that calls several APIs concurrently, with a concurrency limit.
import asyncio
import httpx
async def fetch(client, url, limit):
async with limit:
r = await client.get(url, timeout=10)
r.raise_for_status()
return r.json()
async def fetch_all(urls):
limit = asyncio.Semaphore(10) # at most 10 requests at once
async with httpx.AsyncClient() as client:
return await asyncio.gather(*(fetch(client, u, limit) for u in urls),
return_exceptions=True)The semaphore respects rate limits; return_exceptions=True stops one failure from canceling the rest.
Q44. How do you use type hints in a large codebase?
Type hints (def score(text: str) -> float:) document intent and let a checker such as mypy or Pyright catch bugs before runtime. Useful tools: TypedDict for dict shapes, Protocol for duck-typed interfaces, Literal for fixed options and generics for reusable containers. One catch is that Python itself does not enforce hints at runtime, which is why libraries like Pydantic exist to validate data against them (Q56).
Q45. How do you test Python code that calls an external API?
Use pytest with fixtures for setup, @pytest.mark.parametrize for many input cases, and mocking (unittest.mock.patch or respx/responses for HTTP) so tests do not hit the real service. Test success, failure, and timeout paths. For LLM calls, mock the client and assert on how your code handles the response, not on the model's exact words.
Q46. How do you manage dependencies and environments?
Use an isolated environment per project (venv, or a tool like uv or Poetry), declare dependencies in pyproject.toml, and commit a lock file so every machine installs identical versions. That way, code that passed tests on your laptop runs with exactly the same versions in production, and nothing leaks into the system Python.
Q47. A Python job is too slow. How do you find and fix the bottleneck?
Measure first: cProfile or a sampling profiler such as py-spy to find hot functions, timeit for micro-benchmarks, and tracemalloc for memory. Then fix in this order: a better algorithm or data structure (a set lookup instead of a list scan), vectorization with NumPy or pandas, caching, concurrency, and only then compiled options such as Cython or Numba.
Q48. How do you add safe retries to a flaky network call?
Retry only on transient errors (timeouts, HTTP 429 and 5xx), use exponential backoff with jitter, cap the number of attempts, and make sure the operation is idempotent so a retry cannot, for example, charge a customer twice. The tenacity library handles this with a decorator. This question now comes up often because LLM APIs rate-limit heavily.
Q49. Why use the logging module instead of print()?
logging gives levels (DEBUG to CRITICAL), timestamps, module names, and configurable outputs (console, file, log platforms) that you can change without editing code. In production, teams often log structured JSON so logs are searchable. That searchability matters even more in AI systems, where logging every prompt, tool call, and response is often the only way to see why a model made a particular decision.
Python Interview Questions for Data Engineers
Data engineers write the Python that moves and cleans data before anyone analyses it, so their interviews focus less on syntax and more on what happens when data is large, messy, or late. The questions below follow that path, from reading a file to feeding an AI system.

Q50. How do you process a file that is too large to fit in memory?
You read it in pieces instead of all at once. With pandas, pd.read_csv(path, chunksize=100_000) returns chunks you can aggregate one by one; in plain Python, a generator that yields one line at a time does the same job (see Q16). If you'll read the file many times, converting it to Parquet once is usually the better long-term fix, which leads to the next question.
Q51. Why do data engineers prefer Parquet over CSV?
Parquet stores data by column, compressed, and saves its data types. Because of that column layout, a query that needs 3 of 50 columns reads only those 3, which makes it far faster and cheaper on large datasets. CSV, by contrast, stores plain text row by row, so every read scans the whole file and every load has to guess the types again.
Q52. What makes a data pipeline idempotent, and why does it matter?
A pipeline is idempotent when running it twice gives the same result as running it once. This matters because pipelines fail midway and get re-run; without idempotency, a re-run can load the same rows twice. In Python, you achieve it by writing to a partition and overwriting it (for example, one folder per date) or by upserting on a unique key instead of blindly appending.
Q53. How do you validate data inside a Python pipeline?
You check each batch against an expected schema and rules before passing it on, so bad data stops at the pipeline instead of reaching a dashboard. For row-level records such as API payloads, Pydantic models validate types and required fields. For whole DataFrames, libraries like pandera or Great Expectations check column types, ranges, uniqueness, and null rates.
Q54. In PySpark, what is the difference between a transformation and an action?
Transformations (select, filter, join) only build a plan; nothing runs until an action (count, collect, write) asks for a result. This lazy evaluation lets Spark optimize the whole plan before executing it. A common follow-up is why Python UDFs are slow: they move data between the JVM and Python row by row, so built-in Spark functions should be the first choice.
Q55. How does a data engineer's Python work support RAG and AI systems?
An LLM can only answer from company data if that data is prepared for it, and that preparation is a data engineering job. In Python, that means extracting text from documents, cleaning it, splitting it into chunks, generating embeddings, loading them into a vector database, and then re-running the pipeline incrementally as documents change. That is why many data engineer interviews now include at least one question on chunking strategy or keeping embeddings in sync with source data.
Python Interview Questions for LLM and AI Engineering Roles
Once data engineers prepare the data, AI engineers write Python that sends it to a large language model and turns the reply into something an application can trust. Because an LLM's output is text that can vary from call to call, most questions in this round test how you control, validate, and pay for that output.

Q56. How do you make sure an LLM returns data your code can use?
You define the shape you expect as a Pydantic model and validate the model's reply against it. Most LLM APIs can now be asked for JSON that follows a schema, but the reply can still be malformed, so validation is what turns "usually correct" into something your code can rely on.
from pydantic import BaseModel, Field, ValidationError
class Ticket(BaseModel):
category: str
priority: int = Field(ge=1, le=5)
summary: str
try:
ticket = Ticket.model_validate_json(llm_reply)
except ValidationError as e:
# send the error back to the model and ask it to correct its output
...This is also why Pydantic shows up in so many AI job descriptions: it sits between the model and the rest of the system.
Q57. What should a production-ready LLM API call in Python handle?
A single call looks simple, but in production it has to survive the same failures as any network request, plus a few of its own. A good answer lists a timeout, retries with backoff on rate-limit (429) and server errors (see Q48), a max_tokens limit to cap cost, a low temperature when you need consistent answers, logging of the prompt and response for debugging (see Q49), and keeping the API key in an environment variable rather than in code.
Q58. How do you stream an LLM response, and why would you?
Streaming returns the reply token by token instead of waiting for the full answer, so the user starts reading within a second rather than staring at a spinner. In Python, SDKs expose the stream as an iterator or async iterator, which is the same generator idea from Q16:
async for chunk in stream:
print(chunk.text, end="", flush=True)Q59. What are embeddings, and how do you compare them in Python?
An embedding is a list of numbers that represents a piece of text's meaning, so texts with similar meanings end up close together. To measure how close, you compute cosine similarity, which NumPy handles in one line:
import numpy as np
def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))This comparison is the core of semantic search, and semantic search is the first step of RAG, the subject of the next question.
Q60. Walk through a RAG (retrieval-augmented generation) pipeline in Python.
RAG lets an LLM answer from your own documents by retrieving the relevant passages first and adding them to the prompt. The steps are: load and chunk the documents, embed each chunk, store the vectors, embed the user's question, retrieve the closest chunks, and send the question plus those chunks to the LLM with an instruction to answer only from them. Interviewers usually follow up on chunk size and retrieval quality, because retrieving the wrong chunk means generating the wrong answer.
Q61. How do you control the cost and latency of LLM calls?
Cost and latency both grow with the number of tokens sent and received, so most fixes reduce tokens or calls. You can trim prompts and retrieved context, cap output length, cache answers to repeated questions, route simple tasks to a smaller, cheaper model, and run independent calls concurrently with asyncio (see Q43). Measuring tokens per request is the starting point because you cannot cut what you haven't measured.
Agentic AI Python Interview Questions
The previous section dealt with single LLM calls: one prompt in, one answer out. Agentic AI goes a step further, because the model decides which actions to take, your Python code carries them out, and the loop repeats until the task is done. Interviews for these roles therefore test the code around the model: how tools are defined, how the loop is controlled, and how you stop an agent from doing harm.

Q62. What is an AI agent, and how is it different from a single LLM call?
An AI agent is an LLM placed inside a loop where it can call tools, see the results and decide what to do next. A single call can only answer from what is in the prompt; an agent can look things up, run code, or update a system, and then use those results in its next step. Python implements both the tools and the loop, which is why agentic AI roles still screen heavily for Python.
Q63. How does tool (function) calling work in Python?
You describe each Python function to the model with a name, a description, and a JSON schema for its arguments. The model never runs the function itself; instead, it replies with the tool name and arguments it wants. Your code calls the real function, and you send the result back to the model.
def get_order_status(order_id: str) -> str:
"""Return the delivery status of an order."""
return db.lookup(order_id)
TOOLS = {"get_order_status": get_order_status}Because the description and schema are all the model sees, clear docstrings and type hints (Q44) directly affect how well an agent chooses its tools.
Q64. Write a minimal agent loop.
The loop keeps calling the model until it gives a final answer, running any tools it asks for along the way. The step limit is the most important line, because without it a confused agent can loop forever and run up costs.
def run_agent(task: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = llm.chat(messages, tools=TOOL_SCHEMAS)
if not reply.tool_calls:
return reply.text # final answer
messages.append(reply.as_message())
for call in reply.tool_calls:
try:
result = TOOLS[call.name](**call.arguments)
except Exception as e:
result = f"Tool error: {e}" # let the model recover
messages.append({"role": "tool", "id": call.id, "content": str(result)})
return "Stopped: step limit reached."Note that tool errors are returned to the model as text rather than crashing the loop, so the agent gets a chance to try another approach.
Q65. What is MCP (Model Context Protocol)?
MCP is an open standard, introduced by Anthropic in November 2024, for connecting AI applications to external tools and data. Before that, every framework defined tools in its own format, so you had to rewrite the same integration for each one. With MCP, you write a server once (in Python, using the official SDK) that exposes tools, resources, and prompts, and any MCP-compatible client or agent can use it.
Q66. How do you manage an agent's memory?
An agent's short-term memory is the message history in the current loop, limited by the model's context window. When a long task approaches that limit, you summarise or drop older steps. For anything the agent should remember across sessions, such as user preferences or past decisions, you store it outside the model (in a database or vector store) and retrieve only what is relevant, using the same retrieval idea as RAG (Q60).
Q67. How do you put guardrails on an agent that can take real actions?
Because an agent acts on its own decisions, a wrong decision can now change real systems, not just produce a wrong sentence. The usual safeguards are: validate tool arguments before running them, allow only a fixed list of tools, require human approval for irreversible actions such as payments or deletions, run generated code in a sandbox, and treat text returned by tools or web pages as data, not instructions, to resist prompt injection.
Q68. How do you evaluate an agent?
You cannot check an agent by reading one output, because the same task can succeed or fail through different paths. So you build a test set of realistic tasks and measure the task success rate, check the trajectory (did it call the right tools in a sensible order?), and track cost and steps per task. Many teams run these evals in pytest on every change, sometimes using another LLM as a judge, so a prompt tweak that breaks earlier behavior is caught before release.
Q69. Would you use an agent framework or write the loop in plain Python?
It depends on the complexity. Frameworks such as LangGraph, CrewAI, and LlamaIndex, and the agent SDKs from model providers, offer state management, multi-agent coordination, and tracing out of the box, which saves time on complex workflows. For a simple single-agent task, a plain Python loop like Q64 is easier to debug and has fewer dependencies. Interviewers look for this judgment, not loyalty to one framework.
Python Scripting Interview Questions
Not every Python role builds models or agents; many use Python to automate everyday work such as renaming files, moving reports, and running checks. Scripting questions test whether those small programs are safe to run unattended, and they also come up in DevOps, QA, and data engineering interviews because those roles automate the same kinds of tasks.

Q70. What does if __name__ == "__main__": do?
It runs the block only when the file is executed directly, not when it is imported. When Python runs a file as a script, it sets that file's __name__ to "__main__"; when another file imports it, __name__ is the module's name instead. This lets one file work both as a reusable module and as a command-line script.
Q71. How do you accept command-line arguments in a script?
Use the standard argparse module, which parses arguments, checks their types, and generates a --help message for free.
import argparse
parser = argparse.ArgumentParser(description="Archive old reports")
parser.add_argument("folder")
parser.add_argument("--days", type=int, default=30)
args = parser.parse_args()Q72. How do you work with files and folders in a script?
Use pathlib, because it treats paths as objects and handles Windows and Linux separators for you. The example below finds every CSV file in a folder tree and renames it with a prefix:
from pathlib import Path
for path in Path("reports").rglob("*.csv"):
path.rename(path.with_name(f"2026_{path.name}"))Q73. How do you run a shell command from Python safely?
Use subprocess.run() with the command as a list and check=True, so a failing command raises an error instead of being silently ignored.
import subprocess
result = subprocess.run(["git", "status"], capture_output=True, text=True, check=True)Avoid shell=True with any user-supplied input, because the shell would interpret that input and open the door to command injection. The same caution applies to agents that run commands (Q67).
Q74. How do you schedule a script and keep its secrets out of the code?
Schedule it with cron on Linux, Task Scheduler on Windows, or an orchestrator such as Airflow when it is part of a larger pipeline. Since a scheduled script runs without anyone watching, it should read passwords and API keys from environment variables (os.environ["API_KEY"]) or a secrets manager rather than from the file, and it should log its progress (Q49) so failures can be traced the next morning.
Python Interview Preparation: A 4-Week Plan
Knowing the answers above is only half of Python interview preparation; the other half is producing them under time pressure, often while someone watches you code. The plan below builds in that order, starting with fundamentals because every later round assumes them.
If you want structured preparation, AnalytixLabs' Global Certification Course in Python for Data Science covers the core Python and data skills in this guide, and the Generative AI course builds on them for LLM and agent development.
Week | Focus | What to practice |
|---|---|---|
1 | Fundamentals | Q1–Q25: explain each concept aloud in under a minute, with a one-line example |
2 | Coding | Q26–Q33 plus 2–3 easy and medium problems a day on arrays, strings, dictionaries, and recursion; state the Big-O every time |
3 | Role-specific depth | pandas (Q34–Q41) for analytics roles; Q50–Q55 for data engineering; Q42–Q49 and Q56–Q69 for developer and AI roles |
4 | Projects and mock interviews | Build or polish one project you can explain end to end, then do timed mock interviews with a peer |
For AI-focused roles, the week 4 project matters most, because interviewers increasingly ask you to walk through something you built. A small agent that calls two or three tools, validates its outputs with Pydantic, and has a handful of eval cases in pytest covers most of the topics in this guide, so it gives you material for almost any follow-up question.
Finally, practice reviewing code as well as writing it. Since many teams now expect you to work alongside AI coding assistants, being able to spot the bug in Q33 or Q18 quickly is as valuable as solving a new problem from scratch.
FAQs on Python Interview Questions
What are the most common Python interview questions?
The most common ones cover lists vs tuples, mutability, dictionaries, comprehensions, *args and **kwargsDecorators, generators, exception handling, and the GIL. They appear so often because they reveal whether a candidate understands how Python behaves, not just its syntax. Questions Q1 to Q25 in this guide cover all of them.
Is Python allowed in coding interviews?
Yes, most companies allow Python in coding rounds, and many candidates prefer it because its short syntax leaves more time for problem-solving. Online assessments on platforms such as HackerRank and CodeSignal support it as standard. Some companies now also state whether AI coding assistants are allowed, so check the round format beforehand.
What Python topics are asked in a data engineer interview?
Data engineer interviews focus on handling data at scale: generators and chunked reading, file formats such as Parquet, PySpark, idempotent pipelines, data validation, and orchestration with tools like Airflow. Questions Q50 to Q55, together with the scripting questions, cover these topics.
How should experienced professionals prepare for a Python interview?
Experienced candidates are expected to discuss trade-offs from their own work, so preparation should center on examples, not definitions. Revise concurrency, typing, testing, performance and reliability (Q42 to Q49), and prepare one or two stories about a production problem you diagnosed and fixed.
Do I need to learn agentic AI to get a Python job in 2026?
Not for every role, but it is quickly becoming an advantage. Even analyst and data engineering roles now involve some work with LLMs, and the foundations (async code, Pydantic, API calls, and testing) are useful well beyond agents. Learning those first, then building one small agent, is the most efficient path.