+91 99301 12627
Python & SQL

30 Python Interview Questions for Data Science Freshers (With Answers)

By Mehul Prajapati

Code editor on screen representing Python interview questions for data science freshers
On this page

Short answer: Python interviews for data science freshers usually cover four areas: (1) core Python (data types, lists vs tuples, dictionaries, functions, comprehensions), (2) NumPy basics, (3) Pandas data manipulation (filtering, groupby, merge, missing values), and (4) short practical coding tasks on a dataset. Below are 30 commonly asked questions with concise answers.

Key takeaways

  • Interviewers care more about clear thinking and clean code than tricky syntax.
  • Pandas questions are the most important for data roles.
  • Practise explaining why you chose an approach, for example vectorisation over loops.
  • Expect at least one hands-on data task in many interview processes.

Core Python questions

1. What are Python’s main built-in data types?

Numbers (int, float, complex), str, bool, list, tuple, dict, set and NoneType.

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

Lists are mutable (can change) and use []. Tuples are immutable and use (). Tuples can be used as dictionary keys when their contents are hashable.

3. What is the difference between a list and a set?

Lists keep order and allow duplicates. Sets store unique items and offer fast membership checks.

4. How do dictionaries work, and when do you use them?

Dictionaries store key–value pairs with fast lookup by key. They’re ideal for mappings, counters and grouping data.

counts = {}
for city in ['Mumbai', 'Pune', 'Mumbai']:
    counts[city] = counts.get(city, 0) + 1
# {'Mumbai': 2, 'Pune': 1}

5. What is a list comprehension?

A concise way to build a list:

squares_of_even = [x**2 for x in range(10) if x % 2 == 0]

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

== compares values. is checks whether two variables point to the same object. Use is mainly for None checks.

7. What are mutable and immutable objects?

Mutable objects (list, dict, set) can be changed in place. Immutable objects (int, float, str, tuple) can’t; operations create new objects.

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

A shallow copy creates a new outer object but shares nested objects. A deep copy (copy.deepcopy) copies everything recursively.

9. What are *args and **kwargs?

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.

10. What is a lambda function?

A small anonymous function, often used with sorting or Pandas:

sorted(students, key=lambda s: s['marks'], reverse=True)

11. How does exception handling work?

try:
    value = int(text)
except ValueError:
    value = None
finally:
    print('done')

12. What is a generator?

A function that uses yield to produce values one at a time, saving memory when processing large files or streams.

13. Why is a mutable default argument a bug risk?

Default values are created once. def f(x, items=[]) shares the same list across calls. Use items=None and create the list inside the function.

NumPy questions

14. Why use NumPy arrays instead of Python lists for numbers?

NumPy arrays store data compactly and support vectorised operations implemented in optimised compiled code, which makes them much faster for numerical work.

15. What is broadcasting?

Broadcasting lets NumPy combine arrays of different but compatible shapes, for example adding a 1-D array to each row of a 2-D array without writing loops.

16. How do you calculate the mean of each column of a 2-D array?

import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
arr.mean(axis=0)   # array([3., 4.])

Pandas questions

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

A Series is a one-dimensional labelled array (one column). A DataFrame is a two-dimensional table made of multiple Series.

18. What is the difference between loc and iloc?

loc selects by labels (row index labels and column names). iloc selects by integer positions.

19. How do you handle missing values?

df.isna().sum()                      # count missing values per column
df = df.dropna(subset=['amount'])    # drop rows missing a critical field
df['city'] = df['city'].fillna('Unknown')
df['age'] = df['age'].fillna(df['age'].median())

The right choice depends on why data is missing and how the column is used.

20. How do you group and aggregate data?

df.groupby('region').agg(
    total_sales=('amount', 'sum'),
    orders=('order_id', 'count'),
    avg_order=('amount', 'mean'),
).reset_index()

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

merge combines DataFrames on key columns, like SQL joins. join combines on the index. concat stacks DataFrames vertically or horizontally.

orders.merge(customers, on='customer_id', how='left')

22. How do you remove duplicate rows?

df = df.drop_duplicates(subset=['customer_id', 'order_date'], keep='first')

23. What is the difference between apply, map and vectorised operations?

map transforms values in a Series, often with a dictionary. apply runs a function on rows, columns or values. Vectorised operations (df['a'] * df['b']) are usually fastest; prefer them over apply when possible.

24. How do you create a pivot table?

pd.pivot_table(df, values='amount', index='region',
               columns='month', aggfunc='sum', fill_value=0)

25. How do you work with dates in Pandas?

df['order_date'] = pd.to_datetime(df['order_date'])
df['month'] = df['order_date'].dt.to_period('M')
df['weekday'] = df['order_date'].dt.day_name()

26. How would you detect outliers?

Use visual checks (box plots) and rules such as the IQR method: values below Q1 − 1.5×IQR or above Q3 + 1.5×IQR. Whether to remove them depends on whether they are errors or genuine extreme values.

Practical coding tasks

27. Find the top 5 customers by total spend.

(df.groupby('customer_id')['amount']
   .sum()
   .nlargest(5))

28. Count words in a sentence, ignoring case.

from collections import Counter
Counter('Data science is fun and data is useful'.lower().split())

29. Reverse a string and check if it is a palindrome.

def is_palindrome(s):
    cleaned = ''.join(ch.lower() for ch in s if ch.isalnum())
    return cleaned == cleaned[::-1]

30. Calculate each customer’s percentage share of total revenue.

spend = df.groupby('customer_id')['amount'].sum()
share = (spend / spend.sum() * 100).round(2).sort_values(ascending=False)

How to prepare

  1. Revise core Python data structures and write small functions daily.
  2. Practise Pandas on a realistic dataset: cleaning, groupby, merge, dates. See Python for Data Science.
  3. Pair this with SQL interview questions. Many tasks can be asked in either language.
  4. Be ready to explain your portfolio projects and the Python code behind them.
  5. Practise thinking aloud: clarify the input, state your approach, then code.

Frequently asked questions

How much Python is asked in data science interviews?

Usually core Python plus strong Pandas skills. Advanced topics like decorators or metaclasses are rarely the focus for freshers in data roles.

Will I be asked data structures and algorithms?

Some companies include basic coding problems (strings, lists, dictionaries). Data-focused roles typically emphasise data manipulation over complex algorithms.

Should I write loops or use Pandas in interviews?

Use Pandas or NumPy vectorised operations for data tasks, and explain why. Loops are fine for simple Python logic questions.

How do I practise Python for interviews?

Solve short daily exercises, then do weekly mini-analyses on new datasets, timing yourself and explaining your approach aloud.

Conclusion

Strong fundamentals win Python interviews for data science: data structures, functions, NumPy and especially Pandas, applied to realistic tasks. Practise these 30 questions, explain your thinking clearly, and combine them with SQL and project preparation. Use the job-ready data scientist checklist to cover the rest.

Prepare with hands-on practice in our Python course or Data Science course, or talk to Mehul.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.