# Top 25 Python Data Science Interview Questions (2026 Guide)

Aced (formerly Exponent) publishes a public search API over its indexed pages; the guide is at https://www.aced.io/agents/agent-access.

Source: https://www.aced.io/blog/top-python-data-science-interview-questions
Source observed: 2026-11-04T22:31:23.218Z
Last checked: 2026-11-04T22:31:23.218+00:00
Indexed: 2026-11-05T20:01:44.21+00:00

---

# Top 25 Python Data Science Interview Questions (2026 Guide)

**Data Science**  
**Aced Team · Last updated a month ago**

![Python code example in an IDE](https://storage.ghost.io/c/a5/f5/a5f5c2f0-4c62-43c7-891b-662a0b6d68b3/content/images/2024/07/Python-Code-Example-in-an-IDE-1.jpeg)

Data science interviews often include Python coding questions and [statistical analysis](https://www.aced.io/blog/top-statistics-data-science-interview-questions?ref=exponent-blog.ghost.io). These questions test general Python coding skills and knowledge of libraries such as [Pandas](https://pandas.pydata.org/?ref=exponent-blog.ghost.io) and [NumPy](https://www.machinelearningnuggets.com/numpy-tutorial/?ref=exponent-blog.ghost.io). We compiled these questions to help candidates prepare; each includes what interviewers expect and code where applicable.

**Expert verified:** This guide was written and compiled by [Derrick Mwiti](https://www.udemy.com/user/mwitiderrick/?ref=exponent-blog.ghost.io), a senior data scientist and course instructor, and reviewed by [Satyajit Gupte](https://www.aced.io/coach/Satyajit-Gupte?ref=exponent-blog.ghost.io), a senior machine learning engineer at Pinterest and Target and an interview coach.

## Python Fundamentals

Python is listed as an essential skill in data-science job descriptions for companies including [Microsoft](https://www.aced.io/guides/microsoft-data-scientist-interview?ref=exponent-blog.ghost.io), Google, and Apple.

### 1. Which is faster, Python lists or NumPy arrays?

NumPy arrays are faster for numerical computation and mathematical or statistical operations. They contain homogeneous data types in contiguous memory, whereas Python lists can contain heterogeneous types in non-contiguous memory. Contiguous allocation uses consecutive memory blocks and can reduce memory waste.

This guide contains excerpts from our complete [data science](https://www.aced.io/courses/data-science?ref=exponent-blog.ghost.io) and [software engineering interview](https://www.aced.io/courses/software-engineering?ref=exponent-blog.ghost.io) courses, created with data scientists and engineers from Spotify, Amazon, and Instacart.

**Sneak peek:** [Determine the sample size for an experiment](https://www.aced.io/courses/data-science/statistics-experimentation-questions/determine-sample-size?ref=exponent-blog.ghost.io) includes a Tinder data scientist answer; [What is a P-value](https://www.aced.io/courses/data-science/statistics-experimentation-questions/what-is-p-value?ref=exponent-blog.ghost.io) includes a senior data scientist answer; and [Predict results from a fair coin flip](https://www.aced.io/courses/python-coding-data-scientist-questions/predict-coin-flip?ref=exponent-blog.ghost.io) is available for practice.

### 2. What is the difference between `map()` and `applymap()`?

Both perform elementwise operations. `map` applies to a Series; `applymap` applies to a DataFrame.

### 3. Explain `zip()` and `enumerate()`.

`zip` yields tuples from multiple iterables and stops at the shortest iterable.

```python
list1 = [1, 2, 3, 4, 5]
list2 = ['cow', 'goat', 'hen']
list3 = ['the', 'quick', 'brown', 'fox']
list(zip(list1, list2, list3))
# [(1, 'cow', 'the'), (2, 'goat', 'quick'), (3, 'hen', 'brown')]
```

`enumerate` yields `(index, value)` tuples:

```python
e = enumerate(list3)
list(e)
# [(0, 'the'), (1, 'quick'), (2, 'brown'), (3, 'fox')]
```

### 4. What is a lambda function?

A lambda is an anonymous function declared without `def`. It has one expression and can accept multiple arguments, making code concise but potentially less readable.

```python
def myfunc(n):
    return lambda a, b, c: a + b + c * n

my_func = myfunc(3)
print(my_func(5, 6, 2))
# Output: 17
```

### 5. How do `map`, `reduce`, and `filter` work?

- `map` applies a function to every item in an iterable.
- `filter` keeps items whose test returns true and produces a new iterable.
- `reduce` applies a function from left to right, reducing an iterable to one value.

```python
def myfunc(n):
    return n**2

x = map(myfunc, (1, 2, 3))
list(x)
# [1, 4, 9]
```

```python
names = ["Derrick", "Dennis", "Joe"]

def myFunc(x):
    if x.startswith("D"):
        return True
    return False

final_names = filter(myFunc, names)
for x in final_names:
    print(x)
# Output: Derrick, Dennis
```

```python
from functools import reduce
reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
# 15
```

### 6. Coin change

Given coin denominations and an amount, return the fewest coins needed, or `-1` when no combination works. There are infinitely many coins of each kind.

```python
from typing import List

def coin_change(coins: List[int], amount: int) -> int:
    dp = [float('inf')] * (amount + 1)
    dp[0] = 0

    for i in range(1, amount + 1):
        for coin in coins:
            if i - coin >= 0:
                dp[i] = min(dp[i], dp[i - coin] + 1)

    return dp[amount] if dp[amount] != float('inf') else -1
```

### 7. Find the M largest numbers

For a potentially millions-long unsorted array or file, implement `find_largest(input, m)` to return the largest `M` values. Return `None` for an empty input.

```python
from heapq import heappush, heappop

def find_largest(input, m):
    if not input:
        return None

    max_nums = [float('-inf')]
    for i in input:
        if int(i) > max_nums[0]:
            if len(max_nums) >= m:
                heappop(max_nums)
            heappush(max_nums, int(i))
    return max_nums
```

### 8. Reverse words in an array

Words are separated by spaces. Reverse the order of the words efficiently, in place where the language passes arrays by reference.

```python
def reverse_words(arr):
    n = len(arr)
    mirror_reverse(arr, 0, n - 1)

    word_start = None
    for i in range(n):
        if arr[i] == ' ':
            if word_start is not None:
                mirror_reverse(arr, word_start, i - 1)
                word_start = None
        elif i == n - 1:
            if word_start is not None:
                mirror_reverse(arr, word_start, i)
        else:
            if word_start is None:
                word_start = i
    return arr

def mirror_reverse(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1
```

### 9. What is the difference between `return` and `yield`?

`return` terminates a function and returns a value. `yield` returns an iterator value while preserving the generator’s execution state.

```python
def try_aced():
    return "www.aced.io"
    print("Trying Aced!")  # Not executed

print(try_aced())
# Output: www.aced.io
```

```python
def gen_func(x):
    for i in range(x):
        yield i

generator = gen_func(10)
print(next(generator))  # 0
print(next(generator))  # 1
for x in generator:
    print(x)
# 2, 3, 4, 5, 6, 7, 8, 9
```

### 10. What are global and local variables?

A local variable is defined inside a function or class and is accessible only within that scope. A global variable is defined outside functions or classes and can be accessed throughout the program.

### 11. Uniformly sample words from a text file

```python
import random
import string

class UniformWordSampler:
    def __init__(self, file_path):
        self.file_path = file_path
        self.words = self._load_words_from_file()

    def _load_words_from_file(self):
        """Reads and tokenizes the text file."""
        with open(self.file_path, 'r') as file:
            text = file.read()
        translator = str.maketrans('', '', string.punctuation)
        text = text.translate(translator)
        return text.split()

    def sample_words(self, k):
        """Samples 'k' words uniformly from the tokenized words."""
        if k > len(self.words):
            raise ValueError("Sample size exceeds the number of available words.")
        return random.sample(self.words, k)

def main():
    file_path = "text.txt"
    sampler = UniformWordSampler(file_path)
    sampled_words = sampler.sample_words(5)
    print("Sampled words:", sampled_words)

if __name__ == "__main__":
    main()
```

### 12. What are decorators?

A decorator modifies or extends a Python object without modifying the object itself. Decorators can change function behavior because functions are [first-class citizens in Python](https://nicholaszhan.com/first-class-citizens-in-python-what-you-need-to-know-50b76fab0ced?ref=exponent-blog.ghost.io): they can be returned, passed as arguments, and assigned to variables.

```python
def titlecase_decorator(function):
    def wrapper():
        func = function()
        make_titlecase = func.title()
        return make_titlecase
    return wrapper

@titlecase_decorator
def make_title():
    return 'learning python decorators'

print(make_title())
# Output: 'Learning Python Decorators'
```

### 13. Character-level language model with a vanilla RNN

The guide includes a complete NumPy implementation that reads `input.txt`, maps characters to integer IDs, uses a hidden size of `100`, sequence length `25`, and learning rate `1e-1`, then trains with forward and backward passes, gradient clipping, sampling, and Adagrad updates.

```python
import numpy as np

data = open('input.txt', 'r').read()
chars = list(set(data))
data_size, vocab_size = len(data), len(chars)
print('data has %d characters, %d unique.' % (data_size, vocab_size))
char_to_ix = {ch: i for i, ch in enumerate(chars)}
ix_to_char = {i: ch for i, ch in enumerate(chars)}

hidden_size = 100
seq_length = 25
learning_rate = 1e-1

Wxh = np.random.randn(hidden_size, vocab_size) * 0.01
Whh = np.random.randn(hidden_size, hidden_size) * 0.01
Why = np.random.randn(vocab_size, hidden_size) * 0.01
bh = np.zeros((hidden_size, 1))
by = np.zeros((vocab_size, 1))

def lossFun(inputs, targets, hprev):
    xs, hs, ys, ps = {}, {}, {}, {}
    hs[-1] = np.copy(hprev)
    loss = 0
    for t in range(len(inputs)):
        xs[t] = np.zeros((vocab_size, 1))
        xs[t][inputs[t]] = 1
        hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t - 1]) + bh)
        ys[t] = np.dot(Why, hs[t]) + by
        ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t]))
        loss += -np.log(ps[t][targets[t], 0])

    dWxh = np.zeros_like(Wxh)
    dWhh = np.zeros_like(Whh)
    dWhy = np.zeros_like(Why)
    dbh = np.zeros_like(bh)
    dby = np.zeros_like(by)
    dhnext = np.zeros_like(hs[0])

    for t in reversed(range(len(inputs))):
        dy = np.copy(ps[t])
        dy[targets[t]] -= 1
        dWhy += np.dot(dy, hs[t].T)
        dby += dy
        dh = np.dot(Why.T, dy) + dhnext
        dhraw = (1 - hs[t] * hs[t]) * dh
        dbh += dhraw
        dWxh += np.dot(dhraw, xs[t].T)
        dWhh += np.dot(dhraw, hs[t - 1].T)
        dhnext = np.dot(Whh.T, dhraw)

    for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -5, 5, out=dparam)
    return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs) - 1]
```

### 14. Climbing stairs

For non-negative `n`, return the number of ways to reach the top when each move is one or two steps.

```python
def climb_stairs(n: int) -> int:
    if n <= 1:
        return 1
    ways = [0] * (n + 1)
    ways[0] = 1
    ways[1] = 1
    for i in range(2, n + 1):
        ways[i] = ways[i - 1] + ways[i - 2]
    return ways[n]
```

This question was asked at Microsoft. Related practice: [Explain stack and heap memory allocation](https://www.aced.io/questions/3226/explain-stack-heap-memory-differences?ref=exponent-blog.ghost.io).

## Data Science with Python

These questions test using Python to solve data-science problems.

### 15. Indexing versus slicing in NumPy

- Indexing accesses an element at a particular index.
- Slicing accesses a subset within a range.

```python
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0, 2])
# 3

matrix = np.arange(1, 17).reshape(4, 4)
print(matrix[2:4, 2:4])
# [[11, 12], [15, 16]]
```

This question was asked at Apple. Related practice: [Implement batch normalization using NumPy](https://www.aced.io/questions/3425/implement-batch-normalization-numpy?ref=exponent-blog.ghost.io).

### 16. Simulate dice-roll probabilities

```python
import random

class DiceRollSimulator:
    def __init__(self, trials):
        self.trials = trials

    def roll_dice(self):
        return random.randint(1, 6) + random.randint(1, 6)

    def simulate(self, target_sum):
        success_count = 0
        for _ in range(self.trials):
            if self.roll_dice() == target_sum:
                success_count += 1
        return success_count / self.trials

trials = 1000000
 target_sum = 7
simulator = DiceRollSimulator(trials)
estimated_prob = simulator.simulate(target_sum)
print(f"Estimated probability of rolling a sum of {target_sum}: {estimated_prob:.4f}")
```

### 17. `merge`, `join`, and `concatenate`

- `merge` combines data frames using a specified column and the intersection of elements.
- `join` combines data frames using a unique index. A left join retains exclusive IDs from the left table and produces `NaN` where the right table has no match.
- `concatenate` joins Pandas objects along an axis, such as rows or columns.

### 18. List and dictionary comprehensions

List comprehension creates a list from an iterable:

```python
fruits = ["boy", "bowtie", "cow", "goat", "boat"]
newlist = [x for x in fruits if "b" in x]
# ['boy', 'bowtie', 'boat']
```

Dictionary comprehension creates a dictionary from an iterable:

```python
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
triple_dict1 = {k: v * 3 for k, v in dict1.items() if v > 2}
# {'c': 9, 'd': 12, 'e': 15}
```

### 19. What is Regex? Can it validate an email address?

A [regular expression](https://www.w3schools.com/python/python_regex.asp?ref=exponent-blog.ghost.io) contains special and ordinary characters for matching operations. Python’s `re.match` can validate an address using a pattern such as:

```python
import re

email = 'my.email345@provider-email.io'

def validate_email(email):
    pattern = '^([a-z0-9_.-]+)@([a-z0-9-]+)\\.([a-z0-9-.])+$'
    search = re.match(pattern, email)
    if search:
        return f"{search.group()} is okay"
    return f"{email} is not valid"

print(validate_email(email))
# 'my.email345@provider-email.io is okay'
```

Practice: [Build a Regex Parser](https://www.aced.io/courses/recursion-and-backtracking/basic-regex-parser?ref=exponent-blog.ghost.io).

### 20. Random forests in classification and regression

A random forest is a collection of decision trees. For classification, it selects the class receiving the most votes.

**Classification:**
1. Select random samples with replacement.
2. Build one decision tree for each sample.
3. Obtain a prediction from each tree.
4. Vote.
5. Select the prediction with the most votes.

**Regression:**
1. Select random samples with replacement.
2. Build one decision tree for each sample.
3. Obtain an average from each tree.

**Advantages:**
- Controls overfitting by fitting several trees.
- Higher accuracy than one decision tree.
- Runs efficiently on large datasets.
- Provides feature importance.
- Supports classification and regression.

Related reading: [Top Machine Learning Interview Questions](https://www.aced.io/blog/top-machine-learning-interview-questions?ref=exponent-blog.ghost.io).

### 21. Lists, NumPy arrays, and sets

- **Lists:** Written with `[]`; can store multiple data types, preserve indexed order, and be manipulated.
- **NumPy arrays:** Created with `array()`; store one data type and are efficient for numerical computation.
- **Sets:** Written with `{}`; can store multiple data types, do not allow duplicates, and their items cannot be updated.

Use NumPy arrays for numerical computation and sets to remove duplicates or when values should not change. Related practice: [data structures](https://www.aced.io/questions?role=swe&type=data-structures&ref=exponent-blog.ghost.io).

## Advanced Python and Best Practices

### 22. Common Python string functions

- `split`: splits a string, for example `string.split()`.
- `strip`: removes leading or trailing characters, such as `string.strip(',')`.
- `upper`: converts a string to uppercase, such as `string.upper()`.
- `capitalize`: capitalizes a string, such as `string.capitalize()`.
- `count`: counts occurrences, such as `string.count('the')`.

### 23. Python unit testing

Python’s `unittest` module provides tools for running tests. Test cases assert expected scenarios and help prevent accidental bugs during changes.

```python
def name_as_uppercase(name):
    return name.upper()

def check_balance(amount_paid, loan):
    return amount_paid - loan

import unittest

class TestCases(unittest.TestCase):
    def test_upper(self):
        new_name = name_as_uppercase('derrick')
        self.assertEqual('derrick'.upper(), new_name)

    def test_balance(self):
        balance = check_balance(20, 10)
        self.assertGreaterEqual(balance, 0)

if __name__ == '__main__':
    unittest.main()
```

### 24. Variable types in Python OOP

- **Class variables:** Defined inside a class and accessible to all instances.
- **Instance variables:** Accessible to an individual class instance.
- **Local variables:** Defined inside methods and available only within those methods.

```python
class School:
    language = "English"

    def __init__(self, name, location):
        self.name = name
        self.location = location
```

### 25. Types of Python OOP methods

- **Class methods:** Change class state, access class variables, and take `cls` first.
- **Instance methods:** Access class and instance variables and take `self` first.
- **Static methods:** Do not access class or instance variables and do not require `cls` or `self`.

```python
class School:
    language = "English"

    @classmethod
    def chat_motto(cls, motto):
        return f"The motto is: '{motto}', class is '{cls}'"

    def chat_motto_instance(self, motto):
        return f"The motto is: '{motto}'"

    @staticmethod
    def chat_motto_static(motto):
        return f"The motto is: '{motto}'"
```

## Python Data Science Interview Tips

- Explore mock interviews and practice lessons in our [data science interview course](https://www.aced.io/courses/data-science?ref=exponent-blog.ghost.io).
- Schedule a [free mock interview session](https://www.aced.io/practice?ref=exponent-blog.ghost.io).
- Get [data science interviewing coaching](https://www.aced.io/coaching?category=mock_interviews&role=data-science&ref=exponent-blog.ghost.io) from scientists at top companies.

You can also [browse data scientist interview questions](https://www.aced.io/questions?role=data-science&src=blog) and [book time with a Data Scientist coach](https://www.aced.io/coaching?role=data-science). Coaching includes mock interviews, career coaching, and resume review. The displayed rating is **96% from 5,400 reviews**.

## Aced interview-prep resources

We describe Aced as a tech interview-prep platform offering free interview guides, insider tips, and courses. [Create a free account](https://www.aced.io/signup?src=blog).

### Related courses

- ![Data Science Interview Prep Course](https://images.ctfassets.net/x78yjrjc11pq/3U4C5C0OkDR0UeGch4AmlE/7ad489430b676a088cb973307fe77884/Data_Science_Interview_Prep_Course.jpeg?w=800&h=800) [Data Science Interview Prep Course](https://www.aced.io/courses/data-science) — 8 courses, 5,300 students. Covers mock interviews, frameworks, statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more for roles at Google, Amazon, Microsoft, Meta, Apple, and other companies.
- ![Python Coding Questions for Data Scientists](https://images.ctfassets.net/x78yjrjc11pq/2dzEe4SrDBziupl2qdwul0/f3408fe58ab05caaa454b3f41bc779ce/ds.png?w=800&h=800) [Python Coding Questions for Data Scientists](https://www.aced.io/courses/python-coding-data-scientist-questions) — 18 lessons, 1,000 students. Covers advanced Pandas data manipulation, dataset transformation, statistical tests, experiments, and Python interview problems.

### Related blog posts

- ![Top 25 Statistics Data Science Interview Questions](https://storage.ghost.io/c/a5/f5/a5f5c2f0-4c62-43c7-891b-662a0b6d68b3/content/images/2024/06/Data-Science-Abstraction.jpeg) [Top 25 Statistics Data Science Interview Questions (2026 Guide)](https://www.aced.io/blog/top-statistics-data-science-interview-questions) — A month ago, 14 min read.
- ![Data Science Career Path](https://storage.ghost.io/c/a5/f5/a5f5c2f0-4c62-43c7-891b-662a0b6d68b3/content/images/2022/04/abstract-big-data-1.png) [Data Science Career Path: Your Complete Guide](https://www.aced.io/blog/data-science-career-path) — A month ago, 12 min read.
- ![Data Scientist Resume Guide](https://storage.ghost.io/c/a5/f5/a5f5c2f0-4c62-43c7-891b-662a0b6d68b3/content/images/2024/09/Man-Reviewing-Paperwork-on-Desk-and-Computer.jpeg) [Complete Data Scientist Resume Guide (with FAANG Templates)](https://www.aced.io/blog/data-science-resume) — 13 days ago, 9 min read.
- ![Analytics engineering consulting](https://storage.ghost.io/c/a5/f5/a5f5c2f0-4c62-43c7-891b-662a0b6d68b3/content/images/pmlesson/2021/12/stephen-dawson-qwtCeJ5cLYs-unsplash.jpg) [Your First Analytics Engineering Job Should Be In Consulting](https://www.aced.io/blog/your-first-analytics-engineering-job-should-be-in-consulting) — A month ago, 5 min read.

---

[Read this page’s summary](https://www.aced.io/agents/api/public/v1/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fblog%2Ftop-python-data-science-interview-questions&trace=t_679ff9ab98f3)

## Ask a follow-up about this page

Need a more specific answer? Ask the exact question you have. It returns a fresh, cited answer from Aced (formerly Exponent)’s knowledge base. No account or API key required.

Open this URL with your own question, URL-encoded. Include your question in q. All research inputs are optional; no account or setup.

`GET https://www.aced.io/agents/agent/faq?q={question}&trace=t_679ff9ab98f3`

[Tool guide and examples](https://www.aced.io/agents/agent-access) · [OpenAPI](https://www.aced.io/agents/api/public/v1/openapi.json) · [Page TLDR form](https://www.aced.io/agents/agent-tools/page-tldr?url=https%3A%2F%2Fwww.aced.io%2Fblog%2Ftop-python-data-science-interview-questions). Opening a form does not execute a tool.