Top 25 Python Interview Questions for Data Science Roles

The 25 Python questions that actually come up in data science interviews in India — core language, Pandas, NumPy and practical coding — with short, correct answers and notes on what the interviewer is really testing.

Quick Answer: Python rounds for data science roles test four things — core language behaviour (mutability, copies, comprehensions), NumPy vectorisation, Pandas data manipulation, and practical problem-solving on a real dataset. Pandas takes the largest share of interview time. Short, correct answers with one example beat long recitations.

Data science interviews in India almost always include a Python round, and it is usually the first technical filter. Candidates fail it less from not knowing Python than from knowing it only through tutorials — able to call functions, unable to explain why code behaves the way it does. The 25 questions below are the ones that come up repeatedly for analyst, data scientist and junior ML roles, grouped the way interviews tend to run.

For each, the answer is kept to what you would actually say in the room. Where it helps, there is a note on what the interviewer is listening for.

Part 1: Core Python (Questions 1–8)

Every data science interview starts here, usually in the first fifteen minutes. These questions check whether you can write Python or only call library functions.

Q1. What is the difference between a list and a tuple?

A list is mutable — you can add, remove or change elements. A tuple is immutable once created. Because tuples cannot change, they are hashable when their contents are, so they can be dictionary keys or set members; lists cannot. Tuples are also slightly lighter in memory.

What they are testing: whether you connect immutability to hashability. Mentioning that a function returning several values actually returns a tuple is a good touch.

Q2. How do dictionaries and sets work internally, and why are lookups fast?

Both are hash tables. Python hashes the key to find a slot, so membership checks and lookups are on average constant time, regardless of size. Checking x in my_list scans every element; checking x in my_set does not. That is why converting a large list to a set before repeated membership tests is a standard optimisation.

Q3. What are mutable default arguments, and why are they a problem?

def add_item(item, basket=[]):
    basket.append(item)
    return basket

add_item(1)   # [1]
add_item(2)   # [1, 2]  — same list reused

The default is evaluated once, when the function is defined, so every call shares the same list. The fix is basket=None and creating a new list inside the function.

What they are testing: a genuine understanding of when Python evaluates expressions. This one separates people who have debugged real code from those who have not.

Q4. Explain list comprehensions and generator expressions.

A list comprehension builds the whole list in memory: [x*2 for x in data]. A generator expression, written with parentheses, produces values one at a time on demand. For a large file or a sum over millions of rows, the generator uses almost no memory. Use a comprehension when you need the list again; use a generator when you only iterate once.

Q5. What are *args and **kwargs?

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. They let a function accept a flexible number of inputs, and they are how wrappers pass arguments through to another function — which is exactly how many Pandas and scikit-learn functions forward options.

Q6. What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new outer object but keeps references to the same inner objects. A deep copy recursively copies everything. With a list of lists, changing an inner list after a shallow copy changes it in both. In Pandas, the equivalent trap is modifying a slice and accidentally changing — or failing to change — the original DataFrame, which is why .copy() matters.

Q7. What are lambda functions, and where would you use one in data work?

A lambda is a small anonymous function written in one expression. In data science it appears mostly as a short argument: a sort key, a quick transformation in .apply(), or a custom aggregation. Anything longer than one clear line should be a named function, and saying so is part of a good answer.

Q8. How does exception handling work, and what is the role of finally?

Code that might fail goes in try; specific errors are caught in except; else runs only if nothing failed; finally runs always, which is where you close files or connections. Catching specific exceptions rather than a bare except is the point interviewers listen for — a bare except hides the bugs you most need to see in a data pipeline.

Part 2: NumPy (Questions 9–12)

NumPy questions are fewer but sharper. They check whether you understand why vectorised code is fast.

Q9. Why is a NumPy array faster than a Python list?

A NumPy array stores elements of one type in a contiguous block of memory, and operations run in compiled C code over that block. A Python list stores references to separate objects, each with type information, and a Python loop interprets each step. For numerical work on large data the difference is often one or two orders of magnitude.

Q10. What is vectorisation?

Applying an operation to a whole array at once rather than looping element by element. prices * 1.18 on an array is vectorised; a for loop doing the same multiplication is not. Most performance advice in data science reduces to this: replace Python loops with array or column operations.

Q11. What is broadcasting?

import numpy as np
m = np.array([[1, 2, 3],
              [4, 5, 6]])
m - m.mean(axis=0)   # subtracts each column's mean

Broadcasting lets NumPy combine arrays of different shapes by stretching the smaller one along dimensions of size one, without copying data. Above, a shape (3,) array of column means is applied to every row of a (2, 3) matrix. The rule: dimensions are compared from the right, and each pair must be equal or one of them must be 1.

Q12. What is the difference between a view and a copy in NumPy?

Basic slicing returns a view that shares memory with the original, so changing the slice changes the source. Fancy indexing and boolean masks return copies. This surprises people who slice an array, modify it, and find the original altered — or expect it to be altered and find it untouched.

Part 3: Pandas (Questions 13–20)

This is where most of the interview time goes, because it is where most of the job goes. Expect at least one live exercise from this section.

Q13. What is the difference between loc and iloc?

loc selects by label — index labels and column names — and its slices include the end point. iloc selects by integer position and, like normal Python, excludes the end point. Confusing the two after a filter, when the index is no longer 0 to n, is a classic source of silent errors.

Q14. How do you handle missing values?

First measure: df.isna().sum() per column. Then decide based on why data is missing. Drop rows with dropna() when few are affected and missingness is random; fill with fillna() using the median, mode, a forward fill for time series, or a group-wise value; or add an indicator column when the fact of being missing carries information.

What they are testing: judgement, not syntax. Saying 'I would fill with the mean' without asking why the data is missing is the weak answer. Mentioning that the median resists outliers is the stronger one.

Q15. Explain groupby with an example.

df.groupby('city').agg(
    orders=('order_id', 'count'),
    revenue=('amount', 'sum'),
    avg_order=('amount', 'mean')
)

Groupby follows split-apply-combine: split rows into groups by a key, apply an aggregation to each group, combine the results. Named aggregation, as above, gives readable output columns. Know transform too — it returns a result aligned to the original rows, which is how you add a group average back onto each record.

Q16. What is the difference between merge, join and concat?

merge combines DataFrames on column values, like a SQL join, with how set to inner, left, right or outer. join is a convenience method that joins on the index by default. concat stacks DataFrames vertically or side by side without matching keys. A strong answer mentions checking row counts after a merge — duplicate keys on both sides multiply rows.

Q17. Why is apply slow, and what do you use instead?

apply with a Python function runs that function row by row, so it loses the speed of vectorised operations. Prefer column arithmetic, built-in methods such as .str and .dt accessors, np.where or np.select for conditional logic, and map for lookups. Use apply when logic genuinely cannot be vectorised, and say so.

Q18. What is the SettingWithCopyWarning?

It appears when you assign to something that may be a copy of a slice, so the change may not reach the original DataFrame — for example, chained indexing like df[df.age > 30]['grade'] = 'A'. The fix is a single loc call: df.loc[df.age > 30, 'grade'] = 'A', or an explicit .copy() if you intended a separate frame.

Q19. How do you work with dates in Pandas?

Convert with pd.to_datetime(), then use the .dt accessor for year, month or weekday. Set a datetime index to use resample for daily-to-monthly aggregation and rolling for moving averages. Interviewers often ask for month-on-month growth, which is a resample followed by pct_change().

Q20. How would you handle a CSV too large to fit in memory?

Read only the needed columns with usecols, set compact dtypes — category for repeated strings, smaller integer types — and process the file in pieces with chunksize, aggregating each chunk. Beyond that, push the work into a database with SQL, or use a tool designed for larger data such as Polars or a distributed engine.

Part 4: Practical and Scenario Questions (21–25)

These are asked to see how you think. There is rarely a single right answer; there is a clear wrong one.

Q21. Find the top three products by revenue in each category.

(df.groupby(['category', 'product'], as_index=False)['revenue'].sum()
   .sort_values(['category', 'revenue'], ascending=[True, False])
   .groupby('category')
   .head(3))

Aggregate first, sort within the group, then take the head of each group. Walk through it aloud. If asked for ties, mention rank(method='dense').

Q22. How do you detect and treat outliers?

Look before acting — a box plot or histogram. Common rules are the IQR method, flagging values beyond 1.5 times the interquartile range from the quartiles, and z-scores for roughly normal data. Treatment depends on cause: correct data-entry errors, cap extreme but genuine values, or keep them if they are the point, as in fraud detection.

Q23. How would you encode categorical variables for a model?

One-hot encoding with pd.get_dummies or scikit-learn's OneHotEncoder suits nominal categories with few levels. Ordinal encoding suits ordered categories such as size bands. High-cardinality columns such as city or product ID may need frequency or target encoding, with care to avoid leaking the target. Fit encoders on training data only — that detail matters.

Q24. Why do we split data into train and test sets, and what is data leakage?

The test set estimates performance on data the model has never seen. Leakage is any route by which information from the test set or the future reaches training — scaling on the full dataset before splitting, or using a feature only known after the outcome. Leakage produces excellent scores in a notebook and poor results in production. Our Machine Learning course covers pipelines that prevent it.

Q25. Tell me about a dataset you cleaned and what you found.

Not technically a Python question, but it closes almost every round. Pick one real project. Describe the mess concretely — duplicated customers, inconsistent city spellings, dates in three formats — how you found each problem, what you did, and what changed in the result. Numbers help: rows removed, accuracy before and after.

What they are testing: whether your project is yours. Two follow-up questions reveal a copied notebook immediately.

How to Prepare for the Python Round

Reading answers is not preparation. For every question above, close this page and write the code in a blank notebook from memory. If you cannot, you do not know it yet.

Practise on messy public datasets rather than clean tutorial ones, because live exercises are deliberately untidy. Time yourself on Pandas tasks — a groupby with a filter and a sort should take minutes, not twenty. And practise talking while typing: interviewers score your reasoning, so silence for five minutes followed by correct code scores worse than steady explanation with a small fix along the way.

Do not neglect SQL. Many companies run it in the same round, and several Pandas questions above have a SQL twin — top N per group, joins, date aggregation. If you are still building fundamentals, our Data Science course covers Python, Pandas and SQL with interview-style practice, and the order matters more than speed.

People Also Ask / FAQ

How much Python is needed for a data science job?

Comfortable core Python, strong Pandas, working NumPy, and enough scikit-learn to build and evaluate a model. Advanced software engineering topics matter more for ML engineer roles.

Are coding rounds for data science like software engineering rounds?

Mostly not. Expect data manipulation on a dataset more than algorithm puzzles, though some product companies add one easy data-structures question.

Can I use Google during a live coding interview?

Ask at the start. Many interviewers allow looking up syntax but not solutions. Asking signals honesty and is never held against you.

Should I learn Polars instead of Pandas?

Learn Pandas first — it is what interviews and most existing codebases use. Knowing Polars exists and why it is faster on large data is a useful extra.

How long does it take to prepare for the Python round?

With Python basics in place, three to four weeks of daily practice on real datasets is typical. Starting from zero, plan for two to three months.

Get Interview-Ready in Python and Data Science

Live classes, real datasets and mock interviews — online and in select cities across India Explore the Data Science Course