Background

Top 30 Python Interview Questions for Data Science (Freshers + Experienced) 2026

Prepare with 30 real Python interview questions for data science roles. Covers Pandas, NumPy, data manipulation, and coding challenges. For freshers and experienced candidates.

RV

Ravi Vohra

10 Jul 2026

34 min read

Article graphic

Top 30 Python Interview Questions for Data Science (Freshers + Experienced): The Real Ones

Python is the dominant language in data science. An interviewer can tell within a few questions whether you have written real code or just watched tutorials. The questions in this guide test practical data skills, not theoretical syntax knowledge. Each question includes the answer and, where relevant, code examples.

These are the questions I have asked, been asked, and seen others ask in real data science interviews. They focus on Pandas, NumPy, and data manipulation. The tools you use daily in a data role.

The Fundamentals

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

Lists are mutable. You can change them after creation. Add items, remove items, modify values. Tuples are immutable. Once created, they cannot change. Lists use square brackets. Tuples use parentheses.

Lists are for collections that change. Tuples are for fixed data. Tuples are slightly faster to iterate. Tuples can be used as dictionary keys because they are hashable. Lists cannot.

2. What are list comprehensions? Give an example.

List comprehensions are a concise way to create lists. They replace simple for loops with a single, readable line.

Typescript
1squares = [x**2 for x in range(10)]
2
3evens = [x for x in range(20) if x % 2 == 0]
4
5matrix_flat = [item for row in matrix for item in row]

They are faster than equivalent for loops. They are readable for simple transformations. Avoid nesting them too deeply. A list comprehension inside another list comprehension becomes hard to read.

3. What is a dictionary and how is it used in data science?

A dictionary stores key-value pairs. Keys must be unique and hashable. Values can be anything. Dictionaries are used constantly in data science. Mapping categories to codes. Storing model parameters. Counting frequencies. Representing JSON data.

Typescript
1word_counts = {}
2for word in document:
3    if word in word_counts:
4        word_counts[word] += 1
5    else:
6        word_counts[word] = 1

4. Explain the difference between a function and a method.

A function is a standalone block of code defined with def. A method is a function attached to an object, called on that object using dot notation.

Typescript
1def add(a, b):
2    return a + b
3
4my_list = [3, 1, 2]
5my_list.sort()  # sort is a method of list objects

5. What is a lambda function and when would you use one?

A lambda is an anonymous, one-line function defined without def. It takes arguments and returns an expression. Use it for small operations passed to other functions.

Typescript
1products = [{'name': 'A', 'price': 100}, {'name': 'B', 'price': 50}]
2products.sort(key=lambda p: p['price'])

Lambdas are useful inside sort, map, filter, and apply operations. Keep them simple. If a lambda becomes complex, write a proper function instead.

6. What is the difference between is and double equals?

Double equals checks if values are equal. Is checks if two variables point to the same object in memory. Use double equals for value comparison. Use is for checking identity, like is None or is True.

Typescript
1a = [1, 2, 3]
2b = [1, 2, 3]
3print(a == b)  # True, values are equal
4print(a is b)  # False, different objects in memory

7. How do you handle exceptions in Python?

Use try and except blocks. Try contains code that might fail. Except catches specific exceptions. Finally runs regardless of whether an exception occurred.

Typescript
1try:
2    result = 10 / divisor
3except ZeroDivisionError:
4    result = None
5except TypeError:
6    result = None
7finally:
8    print("Operation attempted")

In data science, exception handling is useful when reading files, parsing dates, or processing data that might have unexpected formats.

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

A shallow copy creates a new object but references nested objects from the original. Changes to nested objects affect both copies. A deep copy creates a completely independent copy including all nested objects.

Typescript
1import copy
2
3original = [[1, 2], [3, 4]]
4shallow = copy.copy(original)
5deep = copy.deepcopy(original)
6
7original[0][0] = 99
8print(shallow[0])  # [99, 2], affected by change to original
9print(deep[0])     # [1, 2], independent copy

NumPy Questions

9. What is NumPy and why is it used in data science?

NumPy provides arrays and mathematical functions for numerical computing. It is faster than pure Python for numerical operations. It forms the foundation for Pandas, scikit-learn, and most data science libraries.

NumPy arrays are homogeneous, all elements must be the same type. They are stored in contiguous memory. Operations are vectorized, applied to entire arrays at once rather than iterating element by element.

10. How do you create NumPy arrays? Show different methods.

Typescript
1import numpy as np
2
3arr1 = np.array([1, 2, 3, 4, 5])
4
5arr2 = np.zeros((3, 4))
6
7arr3 = np.ones((2, 3))
8
9arr4 = np.arange(0, 10, 2)
10
11arr5 = np.random.rand(3, 3)
12
13arr6 = np.linspace(0, 1, 5)

11. What is vectorization and why is it important?

Vectorization performs operations on entire arrays at once rather than iterating through elements. It is implemented in compiled C code under the hood. It is dramatically faster than Python loops for large datasets.

Typescript
1import numpy as np
2arr = np.random.rand(1000000)
3
4# Slow: Python loop
5result_loop = [x * 2 for x in arr]
6
7# Fast: vectorized operation
8result_vec = arr * 2

For a million elements, the vectorized version can be fifty to a hundred times faster. This speed difference is why NumPy and Pandas exist.

12. How do you index and slice NumPy arrays?

Typescript
1arr = np.array([10, 20, 30, 40, 50])
2
3print(arr[0])      # 10, first element
4print(arr[-1])     # 50, last element
5print(arr[1:4])    # [20 30 40], slice
6print(arr[:3])     # [10 20 30], first three
7
8arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
9print(arr2d[0, 1])     # 2, row 0, column 1
10print(arr2d[:, 0])     # [1 4 7], first column
11print(arr2d[1:, :2])   # [[4 5], [7 8]], rows 1-2, columns 0-1

13. What is broadcasting in NumPy?

Broadcasting allows operations between arrays of different shapes. NumPy automatically expands the smaller array to match the larger one, without copying data. It follows specific rules. Arrays must have compatible dimensions. A dimension of 1 is stretched to match.

Typescript
1arr = np.array([[1, 2, 3], [4, 5, 6]])
2row_means = arr.mean(axis=0)
3centered = arr - row_means  # Broadcasting subtracts row_means from each row

14. How do you reshape an array?

Typescript
1arr = np.arange(12)
2print(arr.reshape(3, 4))
3print(arr.reshape(-1, 1))  # -1 infers the dimension

Reshape returns a new view when possible, not a copy. The total number of elements must match.

Pandas Questions

15. What is a DataFrame and how is it different from a Series?

A DataFrame is a two-dimensional labeled data structure with rows and columns. Think of it as a table or spreadsheet. A Series is a single column. A DataFrame is a collection of Series.

DataFrames are the primary data structure in Pandas. Almost all data manipulation happens in DataFrames.

16. How do you read a CSV file and explore the data?

Typescript
1import pandas as pd
2
3df = pd.read_csv('sales.csv')
4
5print(df.head())
6print(df.info())
7print(df.describe())
8print(df.shape)
9print(df.columns.tolist())
10print(df.dtypes)

Head shows first five rows. Info shows column types and non-null counts. Describe gives summary statistics. Shape gives dimensions. Columns gives column names.

17. How do you handle missing values in a DataFrame?

Typescript
1print(df.isnull().sum())
2
3df_dropped = df.dropna()
4
5df['age'] = df['age'].fillna(df['age'].median())
6
7df['category'] = df['category'].fillna('Unknown')
8
9df['income'] = df['income'].fillna(method='ffill')

The approach depends on why values are missing and how much data is missing. Dropping loses data. Filling preserves sample size but can distort distributions. Forward fill uses the last valid observation. The choice requires judgment.

18. How do you filter rows in a DataFrame?

Typescript
1high_value = df[df['total_amount'] > 1000]
2
3north_region = df[df['region'] == 'North']
4
5multiple_conditions = df[(df['region'].isin(['North', 'South'])) & (df['total_amount'] > 500)]
6
7text_filter = df[df['product_name'].str.contains('Candle', case=False)]

Use boolean indexing. Each condition returns a Series of True/False. Combine conditions with & for AND, pipe for OR. Use isin for multiple value matching. Use str accessor for string operations.

19. What is the difference between loc and iloc?

Loc uses labels to access data. Iloc uses integer positions. Loc includes the endpoint in slices. Iloc excludes the endpoint, like Python slicing.

Typescript
1df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['x', 'y', 'z'])
2
3print(df.loc['y'])         # row with index label 'y'
4print(df.loc['x':'y'])     # rows 'x' through 'y', inclusive
5print(df.iloc[1])          # second row, integer position
6print(df.iloc[0:2])        # first two rows, exclusive end

20. How do you group data and calculate aggregations?

Typescript
1region_sales = df.groupby('region')['total_amount'].sum()
2
3region_stats = df.groupby('region').agg({
4    'total_amount': ['sum', 'mean', 'count'],
5    'quantity': 'sum'
6})
7
8category_monthly = df.groupby(['category', df['date'].dt.month])['total_amount'].sum()

Groupby splits data into groups, applies a function, and combines results. Agg applies multiple functions to different columns.

21. How do you merge or join DataFrames?

Typescript
1merged = pd.merge(orders, customers, on='customer_id', how='left')
2
3merged_multi = pd.merge(orders, products, on=['product_id', 'variant_id'], how='inner')
4
5joined = orders.set_index('order_id').join(customers.set_index('customer_id'), how='left')

Inner join keeps only matching rows in both. Left join keeps all left rows, matches from right. Right join keeps all right rows. Outer join keeps all rows from both.

22. How do you apply a function to a DataFrame column?

Typescript
1df['total_with_tax'] = df['total_amount'].apply(lambda x: x * 1.18)
2
3def categorize_order(amount):
4    if amount > 1000:
5        return 'High'
6    elif amount > 500:
7        return 'Medium'
8    else:
9        return 'Low'
10
11df['order_category'] = df['total_amount'].apply(categorize_order)

Apply is flexible but can be slow on large DataFrames. Vectorized operations are faster when possible. Apply is for logic that cannot be vectorized.

23. How do you pivot data in Pandas?

Typescript
1pivot = df.pivot_table(
2    values='total_amount',
3    index='region',
4    columns='category',
5    aggfunc='sum',
6    fill_value=0
7)

Pivot tables reshape data from long to wide format. They are useful for summary views and reporting.

24. How do you handle duplicate rows?

Typescript
1print(df.duplicated().sum())
2
3df_unique = df.drop_duplicates()
4
5df_unique_subset = df.drop_duplicates(subset=['customer_id', 'order_date'])

Check duplicates first. Understand why they exist before removing them. Use subset to check for duplicates on specific columns.

25. How do you sort a DataFrame?

Typescript
1df_sorted = df.sort_values('total_amount', ascending=False)
2
3df_multi_sort = df.sort_values(['region', 'total_amount'], ascending=[True, False])

Sort by one or multiple columns. Control ascending per column.

26. What are the most common Pandas operations you use daily?

Read CSV or Excel. Head, info, describe for exploration. Isnull and sum for missing values. Groupby and agg for aggregation. Merge for combining data. Fillna and dropna for cleaning. Sort_values for ordering. To_csv or to_excel for exporting. Filter with boolean indexing. Apply for custom transformations.

Data Manipulation Scenarios

27. Write code to find the top 3 products by total sales in each region.

Typescript
1top_products = df.groupby(['region', 'product_name'])['total_amount'].sum().reset_index()
2top_products['rank'] = top_products.groupby('region')['total_amount'].rank(method='dense', ascending=False)
3result = top_products[top_products['rank'] <= 3]

Group by region and product. Sum sales. Rank within each region. Filter for rank 3 or less.

28. Given a DataFrame with order_date, write code to calculate month-over-month sales growth.

Typescript
1df['year_month'] = df['order_date'].dt.to_period('M')
2monthly = df.groupby('year_month')['total_amount'].sum().reset_index()
3monthly['prev_month'] = monthly['total_amount'].shift(1)
4monthly['mom_growth'] = ((monthly['total_amount'] - monthly['prev_month']) / monthly['prev_month']) * 100

Create a year-month column. Aggregate sales by month. Use shift to get the previous month's value. Calculate percentage change.

29. How do you identify and handle outliers in a numerical column?

Typescript
1Q1 = df['amount'].quantile(0.25)
2Q3 = df['amount'].quantile(0.75)
3IQR = Q3 - Q1
4lower = Q1 - 1.5 * IQR
5upper = Q3 + 1.5 * IQR
6
7outliers = df[(df['amount'] < lower) | (df['amount'] > upper)]
8
9df_no_outliers = df[(df['amount'] >= lower) & (df['amount'] <= upper)]
10
11df['amount_capped'] = df['amount'].clip(lower, upper)

The IQR method identifies values far from the middle fifty percent. Options after detection include removing, capping, or transforming. The choice depends on the context. An outlier might be an error or a genuinely important extreme value.

30. Write code to clean a column containing inconsistent text data.

Typescript
1df['category'] = df['category'].str.strip()
2df['category'] = df['category'].str.lower()
3df['category'] = df['category'].str.replace(r'[^a-z\s]', '', regex=True)
4
5mapping = {'electrncs': 'electronics', 'furnitre': 'furniture'}
6df['category'] = df['category'].replace(mapping)

Strip whitespace. Convert to consistent case. Remove special characters. Map common misspellings to correct values. Text cleaning is iterative. Look at unique values, identify issues, fix, repeat.

Preparation Tips

Write code without autocomplete during practice. Many interviews use plain text editors or whiteboards. Explain your thought process while coding. The interviewer cares about how you think, not just the final answer. Know Pandas deeply. Most data science Python questions revolve around it.

Practice on real messy datasets. Kaggle and government open data portals are good sources. Understand why you choose one approach over another. There are usually multiple ways to do something in Pandas. Knowing the tradeoffs signals experience.

The Closing Thing

Thirty questions is a lot. You will not get all of them in one interview. But if you understand the concepts and can write the code, you can handle whatever comes. The interviewer wants to see that you have manipulated real data, solved real problems, and can think through a data task out loud.

If you are building these skills, structured practice with mentorship helps. SkillsYard 's Data Science and AI program covers Python, Pandas, machine learning, and real-world projects with live guidance. A free demo class is available. No commitment. Just a session to see if the approach fits.

Related Courses

Programming Courses
BEGINNER
Advance Certification in C++

Master C++ with OOP, STL, memory management & design patterns through real-world projects and expert guidance.

Python ProgrammingObject-Oriented ProgrammingData AnalysisMachine LearningAdvanced Python Concepts
3 months
BEGINNER
Advance Certification in C

Learn C, the language behind operating systems and embedded devices from variables and loops to pointers, memory management, and data structures with hands on projects and expert guidance.

Python ProgrammingObject-Oriented ProgrammingData AnalysisMachine LearningAdvanced Python Concepts
3 months
INTERMEDIATE
Advance Certification in Java

Master Java with OOP, collections, multithreading, and design patterns build scalable applications through real-world projects and expert mentorship.

Java ProgrammingObject-Oriented ProgrammingData Structures & AlgorithmsJava FrameworksAdvanced Java Concepts
6 months
BEGINNER
Advance Certification in Python

Accelerate your career with Advanced Python Certification master enterprise coding, data science, web dev & automation with hands on projects and expert mentorship.

Python ProgrammingObject-Oriented ProgrammingData AnalysisMachine LearningAdvanced Python Concepts
3 months

Frequently Asked Questions

Share this article