Interview prep

Python for Data Science Interview Questions (Top 25)

25 Python for data science interview questions for freshers on NumPy, pandas and scikit-learn, with spoken answers, code, common traps and a short MCQ set.

25QUESTIONSQWhat is a DataFrame?AA table with rows and named columns
  • Interview
  • Python
  • Data Science
  • Freshers

Quick answer: Python for data science interviews test four areas: core Python (lists, mutability, comprehensions), NumPy (vectorisation, broadcasting, axis), pandas (loc vs iloc, groupby, merge, missing values) and basic scikit-learn (train/test split, data leakage, metrics). Prepare a 30-second answer for each topic, then practise writing short pandas code without help.

Most Python for data science interview questions come from a small set of topics. Interviewers want to know three things. Can you write clean Python? Can you handle a messy table in pandas? Do you understand what your machine learning code is doing?

This page covers 25 Python for data science interview questions for freshers. Each one has a 30-second answer to say out loud and a short explanation. The code uses Python 3, NumPy, pandas and scikit-learn.

Note: Read a question, cover the answer and speak first. If you can only answer while reading, you do not know it yet.

Core Python questions

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

30-second answer: Both store ordered items. A list can change after you create it, and a tuple cannot. Use a list for data that grows or changes. Use a tuple for a fixed record, such as a pair of coordinates.

A tuple can be a dictionary key if everything inside it is hashable. A list can never be a key.

distance = {("Hyderabad", "Warangal"): 150}
print(distance[("Hyderabad", "Warangal")])  # 150

Q2. How is a Python list different from a NumPy array?

30-second answer: A list can hold mixed types. A NumPy array usually holds one data type in a compact block of memory, so maths on it is much faster. Operators also behave differently.

import numpy as np

print([1, 2] * 2)            # [1, 2, 1, 2]
print(np.array([1, 2]) * 2)  # [2 4]

Multiplying a list repeats it. Multiplying an array multiplies every element.

Q3. Why is a mutable default argument dangerous?

30-second answer: Python creates the default value once, when the function is defined. If that value is a list, every call without the argument shares the same list.

def add_mark(mark, marks=[]):
    marks.append(mark)
    return marks


print(add_mark(70))  # [70]
print(add_mark(85))  # [70, 85]

The fix is marks=None, followed by if marks is None: marks = [] inside the function.

Q4. What is the difference between a list comprehension and a generator expression?

30-second answer: A list comprehension builds the full list in memory. A generator expression produces one item at a time, so it uses far less memory for large data. You can loop through a generator only once.

squares = [n * n for n in range(4)]
print(squares)                        # [0, 1, 4, 9]
print(sum(n * n for n in range(4)))   # 14

Interview note: A common follow-up is "When would you avoid a generator?" Answer: when you need to index into the result or use it more than once.

Q5. What is a lambda function, and where is it used in data work?

30-second answer: A lambda is a small function without a name that holds a single expression. In data work it is used as a sort key or inside a pandas apply call.

rows = [("Asha", 82), ("Ravi", 91), ("Meena", 75)]
top = max(rows, key=lambda row: row[1])
print(top)  # ('Ravi', 91)

If the logic needs more than one line, write a normal function. It is easier to test.

Q6. What is the difference between == and is?

30-second answer: == checks whether two values are equal. is checks whether two names point to the same object. Use is for None, and == for normal values.

a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False

This is also a popular viva question, because both lines look as if they should print the same thing.

Q7. How do you handle bad values while reading data?

30-second answer: I catch the specific exception I expect, record the bad row and continue. I do not use a bare except, because it hides real bugs.

def to_number(text):
    try:
        return float(text)
    except ValueError:
        return None


print([to_number(t) for t in ["12.5", "NA", "7"]])
# [12.5, None, 7.0]

Add one more line in an interview: "Then I count the None values, so I know how much data was bad." That shows care.

NumPy questions

Q8. What is vectorisation, and why is it faster?

30-second answer: Vectorisation means applying an operation to a whole array instead of looping in Python. The loop runs in compiled code inside NumPy, so it avoids the cost of running Python instructions for every element.

import numpy as np

price = np.array([100, 250, 400])
qty = np.array([2, 1, 3])
print(price * qty)          # [ 200  250 1200]
print((price * qty).sum())  # 1650

Q9. What is broadcasting?

30-second answer: Broadcasting lets NumPy combine arrays of different shapes. It compares shapes from the right. Two dimensions match if they are equal or one of them is 1.

import numpy as np

marks = np.array([[50, 60], [70, 80]])
bonus = np.array([5, 10])
print((marks + bonus).tolist())  # [[55, 70], [75, 90]]

Here shape (2, 2) combines with shape (2,). The bonus row is applied to both rows. Shapes (2, 3) and (2,) would fail, because 3 and 2 do not match.

Q10. What does axis mean in NumPy?

30-second answer: The axis is the direction that gets collapsed. In a 2D array, axis=0 moves down the rows and gives one result per column. axis=1 moves across the columns and gives one result per row.

import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.sum(axis=0))  # [5 7 9]
print(m.sum(axis=1))  # [ 6 15]

A quick check: shape (2, 3) with axis=0 removes the 2 and leaves three values.

Q11. What is the difference between a view and a copy?

30-second answer: A view shares memory with the original array. A copy has its own memory. Basic slicing gives a view, so changing the slice changes the original.

import numpy as np

a = np.array([10, 20, 30, 40])
part = a[1:3]
part[0] = 99
print(a)  # [10 99 30 40]

Use a[1:3].copy() when you need an independent array. Boolean masks and lists of indexes return copies.

pandas questions

Q12. What is the difference between a Series and a DataFrame?

30-second answer: A Series is one labelled column of data. A DataFrame is a table made of columns that share the same row index. df["marks"] gives a Series, while df[["marks"]] gives a DataFrame with one column.

The double bracket matters in machine learning. scikit-learn expects features in two dimensions, so df[["marks"]] works as input and df["marks"] does not. See Series and DataFrame for more examples.

Q13. What is the difference between loc and iloc?

30-second answer: loc selects by label and includes the end of a slice. iloc selects by position and excludes the end, like normal Python slicing.

import pandas as pd

s = pd.Series([10, 20, 30], index=[1, 2, 3])
print(s.loc[1], s.iloc[1])     # 10 20
print(s.loc[1:2].tolist())     # [10, 20]
print(s.iloc[1:2].tolist())    # [20]

Q14. How do you handle missing values?

30-second answer: First I count them and ask why they are missing. Then I drop rows if there are few, fill with a median or most common value if that makes sense, or add a flag column that records the gap.

import pandas as pd

age = pd.Series([21, None, 25, 23])
print(age.isna().sum())                    # 1
print(age.fillna(age.median()).tolist())   # [21.0, 23.0, 25.0, 23.0]

Common mistake: Saying "I fill with the mean" for everything. The mean is pulled by outliers, and it makes no sense for a category such as city.

Q15. How does groupby work?

30-second answer: It follows split, apply, combine. pandas splits rows into groups, applies a function such as mean to each group and combines the results into one table.

import pandas as pd

df = pd.DataFrame({
    "dept": ["CSE", "ECE", "CSE"],
    "marks": [80, 70, 90],
})
print(df.groupby("dept")["marks"].mean().to_dict())
# {'CSE': 85.0, 'ECE': 70.0}

Know the difference between agg and transform. agg returns one row per group. transform returns a result for every original row, which is useful for filling gaps with a group median. Practise on our pandas groupby page.

Q16. What is the difference between merge and concat?

30-second answer: merge joins tables using matching key values, like a SQL join. concat stacks tables on top of each other, or side by side using the index.

Use merge to add customer details to orders. Use concat to combine January and February files with the same columns. The default merge is an inner join, so unmatched rows disappear unless you pass how="left".

Q17. When do you use map, apply and vectorised code?

30-second answer: I try vectorised operations first, because they are fastest. I use map to replace values in one Series with a dictionary. I use apply only when the logic does not fit the other two.

import pandas as pd

grade = pd.Series(["A", "B", "A"])
print(grade.map({"A": 10, "B": 8}).tolist())  # [10, 8, 10]

Values missing from the dictionary become NaN. Check for them after mapping.

Q18. How do you find and remove duplicate rows?

30-second answer: df.duplicated() marks repeated rows and df.drop_duplicates() removes them. I pass subset to say which columns define a duplicate, and keep to say which row to keep.

Before removing anything, decide what "duplicate" means. Two orders with the same customer and amount could be two real orders. Two rows with the same order ID are probably one order recorded twice.

Q19. What is the chained assignment problem?

30-second answer: Code like df[df["marks"] < 35]["result"] = "Fail" selects a temporary table and then changes that. The original may stay the same. The fix is one loc call.

import pandas as pd

df = pd.DataFrame({"marks": [30, 80], "result": ["", ""]})
df.loc[df["marks"] < 35, "result"] = "Fail"
df.loc[df["marks"] >= 35, "result"] = "Pass"
print(df["result"].tolist())  # ['Fail', 'Pass']

Older pandas versions showed SettingWithCopyWarning here. In pandas 3, chained assignment never updates the original. Our guide to Python for data science mistakes covers more bugs of this kind.

Q20. How do you read a CSV that is too big for memory?

30-second answer: I load only the columns I need with usecols, choose smaller data types with dtype, and read the file in parts with chunksize. I summarise each part and combine the summaries.

import pandas as pd

total = 0
for chunk in pd.read_csv("sales.csv", chunksize=100_000):
    total += chunk["amount"].sum()
print(total)

This works for sums and counts. It does not work directly for a median, because medians of parts cannot simply be combined. Mentioning that limit is a strong point.

Visualisation and scikit-learn questions

Q21. Which chart would you choose, and why?

30-second answer: I choose by question. A histogram shows the spread of one number, a bar chart compares categories, a line chart shows change over time and a scatter plot shows the relationship between two numbers. A box plot compares spread and outliers across groups.

Always add axis labels and units. If bars do not start at zero, small differences look large.

Q22. Why do we split data into training and test sets?

30-second answer: A model can memorise its training data. Testing it on unseen rows gives a fairer estimate of real performance. random_state makes the same split repeatable.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

stratify=y keeps class proportions similar in both parts. For time-based data, do not split randomly. Train on the past and test on the future.

Q23. What is data leakage, and how does a pipeline help?

30-second answer: Leakage happens when training uses information that would not be available at prediction time. For example, scaling the full dataset before splitting lets test values affect the training data. A pipeline fits each step on training data only.

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

Interview note: Expect "How would you notice leakage?" A score that looks too good, or one feature that predicts almost everything, is a warning sign.

Q24. How do you convert categories into numbers?

30-second answer: For categories without order, such as city, I use one-hot encoding. For real order, such as small, medium and large, I use ordinal encoding with the order stated.

Numbering cities 0, 1 and 2 tells a linear model that one city is "greater" than another, which is false. In scikit-learn, set OneHotEncoder(handle_unknown="ignore") so a new category does not crash prediction. LabelEncoder is meant for the target column, not for input features.

Q25. Why can accuracy be misleading?

30-second answer: If 95 out of 100 transactions are genuine, a model that always says "genuine" gets 95% accuracy and catches no fraud. For imbalanced classes I check precision, recall, F1 and the confusion matrix.

Precision asks, "Of the items I flagged, how many were right?" Recall asks, "Of the items I should have flagged, how many did I find?" Link your choice to the cost of each error. Revise the topic with machine learning basics questions.

Viva questions and MCQ self-check

Python for data science viva questions are usually shorter than interview questions. Examiners ask for a definition, one example and one difference. Practise Q1, Q10, Q12, Q13 and Q22 in that format.

Now try this short Python for data science MCQ set. Answer first, then check the key below.

  1. What is the shape of np.zeros((3, 4)).sum(axis=0)? (a) (3,) (b) (4,) (c) (3, 4)
  2. Which one excludes the end of a slice? (a) loc (b) iloc (c) both
  3. What does np.nan == np.nan return? (a) True (b) False (c) an error
  4. What is the default join in pd.merge? (a) left (b) outer (c) inner
  5. Which method returns one value for every original row? (a) transform (b) agg (c) size
  6. Which object can be a dictionary key? (a) list (b) set (c) tuple of strings
  7. Where should a scaler be fitted? (a) all data (b) training data (c) test data
  8. Which metric asks how many real positives were found? (a) precision (b) recall (c) accuracy

Answers: 1-b, 2-b, 3-b, 4-c, 5-a, 6-c, 7-b, 8-b.

If you missed question 3, remember this: use isna() to find missing values, never ==.

How to prepare Python for data science interview questions in 10 days

Day What to do Test yourself
1-2 Q1 to Q7 Predict every output before running it
3-4 Q8 to Q11 Write the shape of each result on paper
5-7 Q12 to Q20 Clean and summarise one new CSV without help
8 Q21 to Q25 Explain leakage to a friend
9 Project practice Talk about one project for five minutes
10 Mock interview Ten random questions, two minutes each

Reading alone will not be enough. Solve our Python for data science practice problems during days 1 to 7. Then build one of these Python for data science projects, because most interviews move from theory to "show me what you built". The data science course guide shows how Python fits with SQL, statistics and machine learning.

Pro tip: After each answer, add one line from your own work: "In my project I used a left merge because some customers had no orders." One real example is stronger than three definitions.

Frequently asked questions

Which Python topics are most common in data science interviews for freshers?

Expect core Python data types, list comprehensions and functions, then NumPy arrays and broadcasting, and a lot of pandas: filtering, groupby, merge and missing values. Most interviewers finish with train/test split, data leakage and evaluation metrics.

Do I need data structures and algorithms for a data science interview?

You need the basics. Many companies use a coding test with easy string, list and dictionary problems before the data round. Advanced topics such as dynamic programming are less common for data roles, but the exact test depends on the company.

How long does it take to prepare these 25 questions?

If you already know Python and pandas, about 10 days at two hours a day is a realistic target. If pandas is new to you, plan for four to six weeks, because you need to write code and not only read answers.

Are Python for data science MCQs asked in placement tests?

Some online tests include multiple-choice questions on Python output, NumPy shapes and pandas functions. The best preparation is to predict the output of short snippets by hand before running them.

What should I do if I forget a pandas function in an interview?

Say what you want to do in plain words, then write the closest code you remember. Interviewers usually care more about the correct steps and edge cases than about exact parameter names.


Want a trainer to test you on these questions? Book a free demo class for the Data Science with AI course. Every trainer has at least 14 years of experience, and the course includes mock interviews.

Found this useful? Share it: LinkedIn Facebook WhatsApp

Written by

Siva Prasad Galaba

Staff Engineer & Founder, CodeBegun

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaching the next generation to code the way the industry actually works.

Back to all articles
Chat with us