JobPrep

Python Developer Interview Questions and Answers: The 25 Most Asked in 2026

The 25 most commonly asked Python developer interview questions with clear, professional, interview-ready answers. Covers data types, OOP, decorators, the GIL, memory management, async, testing, Django vs FastAPI and a live coding question, updated for Python 3.15.

These are the 25 questions that come up most often in Python developer interviews, from fresher level up to around three years of experience. Each answer is written the way you should say it in the interview: a clear definition first, then the key differences, then a real example.

Most answers also include a short code example. You don't need to recite it. It's there in case the interviewer says "can you show me?" or asks you to write it on a whiteboard or shared screen.

The questions are split into five pages:

  • Page 1: core language basics
  • Page 2: functions and object-oriented programming
  • Page 3: Python internals
  • Page 4: concurrency, type hints, tooling and testing
  • Page 5: real-world scenarios and a live coding question

How to prepare: read an answer, close it, then say it out loud in your own words. Being able to explain it clearly without looking is what the interview actually tests.

For deeper reading, the official Python documentation is free and is the most reliable reference. The relevant page is linked under the answers where it helps.


The 25 Questions

Q1 What makes Python different from languages like Java or C++, and why do companies use it?

Python is a high-level, interpreted, dynamically typed language, whereas Java and C++ are statically typed and require explicit type declarations. Python has simpler syntax and needs much less boilerplate code, which makes development faster and the code easier to read and maintain.

Another major advantage is its extensive ecosystem of libraries and frameworks. Companies use Python for web development (Django, Flask, FastAPI), data analysis (Pandas, NumPy), machine learning and AI (PyTorch, TensorFlow, scikit-learn), and automation and scripting.

The main limitation is execution speed. Pure Python code runs slower than compiled languages like C++. However, performance-critical libraries such as NumPy are implemented in C, and for most business applications, faster development matters more than raw execution speed.

Why they ask: to check that you understand both Python's strengths and its trade-offs.

Q2 What is the difference between a list, a tuple, a set and a dictionary? When do you use each?

A list is an ordered, mutable collection that allows duplicate values. It is used when the order of items matters and the data needs to change, for example a list of search results.

A tuple is ordered but immutable, so it cannot be modified after creation. It is used for fixed data such as coordinates or database records. Because it is hashable, a tuple can also be used as a dictionary key.

A set is an unordered collection of unique elements. It is used to remove duplicates and for fast membership checks: checking whether an item exists in a set takes constant time on average, while in a list it takes linear time.

A set itself is mutable: elements can be added or removed with methods such as add() and remove(). However, the elements inside a set must be hashable, which in practice means immutable types such as numbers, strings and tuples. A list or a dictionary cannot be stored in a set. When an immutable set is needed, for example as a dictionary key or as an element of another set, Python provides frozenset.

A dictionary stores data as key-value pairs and provides fast lookup by key. It is used for mappings such as user IDs to user details, or application settings. Since Python 3.7, dictionaries also preserve the insertion order of their keys.

A dictionary is mutable: items can be added, updated and deleted. The keys must be hashable and therefore immutable, such as strings, numbers or tuples of immutable values, because Python uses the key's hash to find the value quickly. The values have no such restriction and can be any type, including mutable objects like lists or other dictionaries. Since Python 3.15, there is also a built-in frozendict for cases where the whole dictionary must be immutable.

Code example (if the interviewer asks):

results = ["laptop", "phone", "laptop"]   # list: ordered, allows duplicates
point = (12.5, 77.6)                       # tuple: fixed values
allowed_ids = {101, 102, 103}              # set: unique values, fast lookup
prices = {"apple": 40, "milk": 60}         # dict: key-value pairs

allowed_ids.add(104)          # sets are mutable
# allowed_ids.add([105])      # TypeError: list is unhashable
frozen_ids = frozenset({1, 2})  # immutable set

prices["bread"] = 35          # dicts are mutable
cart = {"user_1": ["milk"]}   # values can be mutable (a list)
locations = {(12.9, 77.6): "Bengaluru"}  # tuple key is allowed
# bad = {["a"]: 1}            # TypeError: list cannot be a key

Why they ask: choosing the right data structure is a basic but important skill. See the data structures tutorial.

Q3 What is the difference between mutable and immutable types, and why does it matter?

Mutable objects can be changed after they are created. Examples are lists, dictionaries and sets. Immutable objects cannot be changed. Examples are integers, floats, strings, tuples and, since Python 3.15, the built-in frozendict. When we try to modify an immutable object, Python does not change the original object. Operations such as += on a string create a new object and assign it to the same variable, while direct changes, such as assigning to an item of a tuple, raise a TypeError.

This matters most for function arguments. A common bug is using a mutable object, such as an empty list, as a default argument. Default values are evaluated only once, when the function is defined, so the same list is shared across all calls and keeps growing. The correct approach is to use None as the default and create a new list inside the function.

Code example (if the interviewer asks):

# Trying to modify immutable objects
name = "Asha"
print(id(name))
name += " Rao"         # creates a new string object
print(id(name))        # different id: a new object

point = (1, 2)
# point[0] = 5         # TypeError: tuples cannot be changed

# Bug: the same list is reused on every call
def add_item(item, items=[]):
    items.append(item)
    return items

add_item("a")  # ['a']
add_item("b")  # ['a', 'b']

# Fix: create a new list for each call
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Why they ask: this is a very common real-world bug and shows whether you understand how Python handles objects.

Q4 What is the difference between is and ==?

The == operator compares the values of two objects, while the is operator checks whether two variables refer to the same object in memory.

For example, two separate lists [1, 2, 3] are equal with ==, but is returns False because they are two different objects.

The is operator should be used for comparisons with singletons such as None, for example if value is None:, as recommended by PEP 8. It should not be used to compare numbers or strings, because the result depends on Python's internal caching and is not reliable.

Code example (if the interviewer asks):

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True  - same values
print(a is b)  # False - different objects

Why they ask: to check that you understand the difference between object identity and equality.

Q5 What are *args and **kwargs?

*args allows a function to accept any number of positional arguments, which are collected into a tuple. **kwargs allows a function to accept any number of keyword arguments, which are collected into a dictionary.

They are commonly used in wrapper functions and decorators, where the wrapper needs to accept and pass on the arguments of the original function without knowing them in advance.

The same symbols are also used for unpacking: func(*my_list) passes list items as separate positional arguments, and func(**my_dict) passes dictionary items as keyword arguments.

Code example (if the interviewer asks):

def log(message, *args, **kwargs):
    print(message, args, kwargs)

log("Saved", 1, 2, user="asha")
# Saved (1, 2) {'user': 'asha'}

Why they ask: it is the foundation for understanding decorators, which is usually the next question.

Q6 What is a decorator? Can you write one?

A decorator is a function that takes another function as input and returns a modified version of it, adding extra behaviour without changing the original function's code. The @decorator syntax is shorthand for func = decorator(func).

Common use cases are logging, measuring execution time, caching, authentication checks and retry logic. Frameworks use decorators heavily, for example @app.route() in Flask and @app.get() in FastAPI.

Inside a decorator, functools.wraps should be used on the wrapper function. It preserves the original function's name and docstring, which is important for debugging and logging.

Code example (if the interviewer asks): a decorator that measures execution time.

import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
        return result
    return wrapper

@timed
def generate_report():
    ...

Why they ask: decorators show that you understand functions as first-class objects. The functools documentation also covers built-in decorators such as cache.

Q7 What is a generator, and why would you use one instead of a list?

A generator is a function that returns values one at a time using the yield keyword, instead of returning all values at once. It produces each value only when it is requested, which is called lazy evaluation.

The main advantage is memory efficiency. A list stores all its elements in memory, while a generator holds only the current value. This makes generators suitable for processing large files, data streams or very large sequences.

The limitation is that a generator can be iterated only once and does not support indexing. If the data needs to be reused or accessed by position, a list is the better choice.

Code example (if the interviewer asks): reading only error lines from a large log file.

def read_errors(path):
    with open(path) as f:
        for line in f:
            if "ERROR" in line:
                yield line

for line in read_errors("app.log"):
    print(line)

Why they ask: to check whether you think about memory usage and performance. See the functional programming HOWTO.

Q8 What is a list comprehension, and when should you not use one?

A list comprehension is a concise way to create a new list from an iterable in a single expression, with an optional condition. It is generally more readable and slightly faster than an equivalent for loop with append().

A generator expression uses the same syntax with parentheses instead of square brackets. It produces values lazily, which saves memory when the result is used only once, for example inside sum().

A list comprehension should not be used when the logic becomes complex, such as multiple nested loops with several conditions, because a regular loop is easier to read and debug. It should also not be used only for side effects such as printing or saving data, because its purpose is to build a new list.

Code example (if the interviewer asks):

squares = [n * n for n in numbers if n > 0]   # list comprehension
total = sum(n * n for n in numbers)           # generator expression

Why they ask: to check that you write readable code, not just short code.

Q9 Explain object-oriented programming in Python: classes, inheritance and super().

Object-oriented programming organises code into classes and objects. A class defines the attributes and methods, and an object is an instance of that class. Python supports the four main OOP principles: encapsulation, inheritance, polymorphism and abstraction.

Inheritance allows a child class to reuse and extend the functionality of a parent class. super() is used to call methods of the parent class, most commonly inside __init__, so the parent class initialises its part of the object first.

Python also supports multiple inheritance. The order in which Python searches parent classes for a method is called the Method Resolution Order (MRO), and it can be checked with ClassName.mro().

In real projects, composition is often preferred over deep inheritance hierarchies, because it keeps the code more flexible and easier to maintain.

Code example (if the interviewer asks):

class Order:
    def __init__(self, items):
        self.items = items

class SubscriptionOrder(Order):
    def __init__(self, items, months):
        super().__init__(items)
        self.months = months

Why they ask: OOP is part of almost every Python interview. See the classes tutorial.

Q10 What is the difference between an instance method, a @classmethod and a @staticmethod?

An instance method is the default type of method. It takes self as its first parameter and can access and modify the object's attributes.

A class method is defined with @classmethod and takes cls as its first parameter. It works with the class rather than a specific instance, and is commonly used for alternative constructors, such as creating an object from a dictionary or a JSON string. Because it uses cls, a class method also works correctly with subclasses.

A static method is defined with @staticmethod and takes neither self nor cls. It behaves like a regular function that is placed inside the class because it is logically related to it, such as a validation or formatting helper.

Code example (if the interviewer asks):

class User:
    def __init__(self, name, email):        # instance method
        self.name = name
        self.email = email

    @classmethod
    def from_dict(cls, data):               # alternative constructor
        return cls(data["name"], data["email"])

    @staticmethod
    def is_valid_email(email):              # helper, no self or cls
        return "@" in email

Why they ask: to check that you have practical experience writing classes.

Q11 What is the GIL, and is it still a limitation in 2026?

The GIL (Global Interpreter Lock) is a mutex in CPython, the standard Python implementation, that allows only one thread to execute Python bytecode at a time. Because of this, multithreading does not provide true parallelism for CPU-bound tasks.

The GIL is released during I/O operations such as network requests, file access and database queries. Therefore, multithreading and asyncio are still effective for I/O-bound applications such as web servers and API clients. For CPU-bound work, multiprocessing is used instead, or libraries like NumPy that perform heavy computation in C.

Since Python 3.14, a free-threaded build of CPython without the GIL is officially supported (PEP 779). However, it is optional and separate from the default build, and some third-party libraries do not fully support it yet.

Why they ask: it is one of the most common Python internals questions. Mentioning the free-threaded build shows your knowledge is up to date. See the official free-threading guide.

Q12 How does Python manage memory?

Python manages memory automatically using a private heap, reference counting and a garbage collector.

Every object keeps a reference count, which is the number of references pointing to it. When the count reaches zero, the memory is released immediately.

Reference counting cannot handle circular references, where two objects refer to each other. For these cases, Python has a cyclic garbage collector that periodically finds and removes groups of unreachable objects. It can be inspected and controlled using the `gc` module.

The del statement removes a reference to an object, not the object itself. The object is freed only when no references to it remain. Memory leaks in Python applications are usually caused by references that are kept unintentionally, such as global caches or lists that keep growing.

Why they ask: to check that you understand what happens behind your code.

Q13 What is the difference between a shallow copy and a deep copy?

A shallow copy creates a new outer object, but the nested objects inside it are still shared with the original. A deep copy creates a new object and recursively copies all nested objects, so the copy is completely independent.

A shallow copy can be made with copy.copy(), list.copy() or slicing, and a deep copy with copy.deepcopy(). The difference only matters for nested data, such as a list of lists or a dictionary containing lists. A deep copy is used when nested data must be changed without affecting the original, for example when creating a modified version of a configuration dictionary.

Code example (if the interviewer asks):

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0].append(99)
print(shallow[0])  # [1, 2, 99] - inner list is shared
print(deep[0])     # [1, 2]     - fully independent

Why they ask: shared nested data causes real bugs. See the `copy` module documentation.

Q14 What are dunder (magic) methods? What is the difference between __str__ and __repr__?

Dunder (double underscore) methods, also called magic methods, are special methods that define how objects behave with built-in operations. For example, __init__ initialises an object, __len__ is called by len(), __eq__ defines the == comparison and __add__ defines the + operator.

__str__ returns a readable, user-friendly string and is used by print() and str(). __repr__ returns an unambiguous representation intended for developers. It is used in the interactive console and in logs, and ideally it shows how to recreate the object.

If __str__ is not defined, Python falls back to __repr__, so __repr__ is the more important one to implement.

Code example (if the interviewer asks):

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __str__(self):
        return f"₹{self.amount}"          # print(m) -> ₹500

    def __repr__(self):
        return f"Money({self.amount!r})"  # console -> Money(500)

Why they ask: to check your understanding of Python's object model. See the data model reference.

Q15 How do you handle exceptions in Python? What is a context manager?

Exceptions are handled using try, except, else and finally blocks. The try block contains code that may raise an exception, except handles specific exceptions, else runs only if no exception occurred, and finally always runs, which makes it suitable for cleanup.

Best practice is to catch specific exceptions such as ValueError or KeyError instead of using a bare except:, which can hide real bugs. For application-specific errors, custom exceptions are created by inheriting from Exception, for example class PaymentFailedError(Exception).

A context manager manages resources automatically using the with statement. It guarantees that setup and cleanup happen, even if an error occurs. Context managers are used for files, database connections, locks and transactions. Custom context managers can be created with the `contextlib` module or by implementing __enter__ and __exit__.

Code example (if the interviewer asks):

try:
    amount = int(user_input)
except ValueError:
    print("Please enter a valid number")
else:
    print("Amount accepted")
finally:
    print("Validation finished")

with open("report.csv") as f:   # file is closed automatically
    data = f.read()

Why they ask: proper error handling is essential for reliable production code. See the errors and exceptions tutorial.

Q16 When would you use threading, multiprocessing or asyncio?

The choice depends on whether the task is I/O-bound or CPU-bound.

Threading is suitable for I/O-bound tasks such as calling APIs or reading files, especially when using blocking libraries. Threads run concurrently, but because of the GIL, only one thread executes Python code at a time.

asyncio is also used for I/O-bound tasks. It is more efficient for a very large number of concurrent operations, such as thousands of network requests, because it uses a single-threaded event loop with async and await. It requires libraries that support async, such as httpx or asyncpg.

Multiprocessing is used for CPU-bound tasks such as image processing or heavy calculations. Each process has its own Python interpreter and memory, so it achieves true parallelism across CPU cores.

For example, downloading 500 web pages is a good use case for asyncio, while resizing 500 images is a good use case for multiprocessing.

Why they ask: this is the practical follow-up to the GIL question. See the asyncio and multiprocessing documentation.

Q17 Does Python enforce type hints? How are they used?

No, Python does not enforce type hints at runtime. They are annotations that describe the expected types of variables, parameters and return values, for example def get_user(user_id: int) -> User | None:.

Type hints improve code readability, enable better autocomplete and error detection in editors such as VS Code, and allow static type checkers such as mypy to find type errors before the code runs.

Some libraries use type hints at runtime. Pydantic uses them for data validation, and FastAPI uses them to validate request data and generate API documentation automatically.

In modern Python codebases, type hints are standard practice, especially in larger teams, because they make the code easier to understand and safer to change.

Why they ask: most modern projects use type hints. See the `typing` documentation.

Q18 What is a virtual environment, and how do you manage dependencies?

A virtual environment is an isolated Python environment with its own set of installed packages, separate from the system Python and from other projects. It prevents dependency conflicts, for example when two projects need different versions of the same library. It can be created with the built-in `venv` module.

Dependencies are listed in a requirements.txt file or, in modern projects, in pyproject.toml. For reproducible builds, a lock file records the exact versions of all packages, including sub-dependencies, so every environment installs the same versions.

Common dependency management tools are pip, Poetry and uv. uv is a fast, modern tool that creates the virtual environment, installs packages and generates a uv.lock file, so the same environment can be recreated on any machine.

Code example (if the interviewer asks):

# Classic approach
python -m venv .venv
pip install -r requirements.txt

# With uv
uv add requests
uv sync   # recreate the locked environment on another machine

Why they ask: to check that you can avoid "it works on my machine" problems.

Q19 How do you test your Python code?

I use pytest, the most widely used testing framework in Python. Tests are written as functions whose names start with test_, and they use plain assert statements.

The main pytest features I use are fixtures for reusable test setup, such as a test database or sample data, parametrize to run the same test with multiple inputs, and mocking with unittest.mock to replace external services such as payment gateways or third-party APIs, so that tests are fast and reliable.

I write unit tests for individual functions and integration tests for components that work together. Tests should check behaviour rather than internal implementation, so the code can be refactored without breaking them. All tests run automatically in the CI pipeline.

Code example (if the interviewer asks):

import pytest

@pytest.mark.parametrize("price, expected", [(100, 90), (0, 0)])
def test_discount(price, expected):
    assert apply_discount(price, percent=10) == expected

Why they ask: testing practices show how reliable your code will be in a team.

Q20 What is PEP 8, and how do you maintain code quality?

PEP 8 is the official style guide for Python code. It defines conventions such as snake_case for variables and functions, PascalCase for class names, four-space indentation, maximum line length and import ordering. Following it keeps code consistent and readable across a team.

To maintain code quality, I rely on automated tools rather than manual checks. Ruff is a fast linter and formatter that detects style issues and common errors and formats the code automatically. It runs in the editor on save and in the CI pipeline.

Beyond style, code quality also includes meaningful names, small single-purpose functions, type hints, docstrings, automated tests and regular code reviews.

Why they ask: teams need developers whose code is easy for others to read and maintain.

Q21 A Python script is running slowly. How would you improve its performance?

The first step is to profile the code to find the actual bottleneck instead of guessing. Python provides the built-in `cProfile` module, and Python 3.15 added a new `profiling` package with a low-overhead sampling profiler.

After identifying the slow part, I would apply optimisations in order of impact:

  1. Algorithm and data structures: for example, replacing repeated list lookups inside a loop with a set or dictionary.
  2. I/O: reducing the number of database queries, such as fixing the N+1 query problem by fetching related data in one query.
  3. Caching: using functools.lru_cache or functools.cache for repeated expensive function calls.
  4. Optimised libraries: using NumPy or Pandas for numerical work, since they run operations in C.
  5. Concurrency: using multiprocessing for CPU-bound work or asyncio for I/O-bound work.

If these steps are not enough, the performance-critical parts can be rewritten using tools like Cython or a compiled language.

Why they ask: this is a problem-solving question, and "profile first" is the key point they want to hear.

Q22 How would you process a very large CSV or JSON file?

A large file should be processed line by line or in chunks, instead of loading it fully into memory.

For CSV files, the built-in `csv` module reads one row at a time while iterating, so memory usage stays low even for very large files. With Pandas, the chunksize parameter of read_csv() processes the file in smaller parts.

For JSON, json.load() reads the entire file into memory, so it is not suitable for very large files. A better format for large datasets is JSON Lines, where each line is a separate JSON object that can be processed one at a time. For a single large JSON document, a streaming parser such as ijson can be used.

Code example (if the interviewer asks):

import csv

total = 0
with open("sales.csv", newline="") as f:
    for row in csv.DictReader(f):     # one row in memory at a time
        total += float(row["amount"])

Why they ask: to check that you consider memory limits when working with real-world data.

Q23 Django, Flask or FastAPI: which would you choose, and why?

The choice depends on the project requirements.

Django is a full-featured framework that includes an ORM, authentication, an admin panel and built-in security features. It is suitable for large, database-driven applications such as e-commerce platforms, content management systems and internal dashboards.

Flask is a lightweight micro-framework that provides routing and request handling, and lets developers choose additional libraries as needed. It is suitable for small applications, microservices and prototypes.

FastAPI is a modern framework for building APIs. It uses type hints and Pydantic for automatic request validation, generates interactive API documentation automatically and supports async natively. It is suitable for high-performance REST APIs and for serving machine learning models.

For a complete web application, I would choose Django. For an API-focused service, I would choose FastAPI. In an existing team, I would follow the framework already in use for consistency.

Why they ask: to check that you can make and justify a technical decision.

Q24 What new features in recent Python versions have you found useful?

Recent Python versions have added several useful features:

  • Python 3.15 (October 2026): lazy imports with the new lazy keyword, which delays loading a module until it is first used and improves startup time. It also added a built-in frozendict, an immutable dictionary type.
  • Python 3.14: official support for the free-threaded build without the GIL, and template strings (t-strings), which work like f-strings but return a Template object that libraries can process safely.
  • Python 3.10: structural pattern matching with match and case.
  • Python 3.8: the walrus operator (:=), which assigns a value inside an expression.

In my day-to-day work, I regularly use f-strings, type hints, dataclasses and pattern matching. I also follow the official "What's New" documentation for each release.

Code example (if the interviewer asks):

lazy import json                      # Python 3.15: loaded on first use

match command:                        # Python 3.10: pattern matching
    case "start":
        start_server()
    case "stop":
        stop_server()

if (count := len(items)) > 10:        # Python 3.8: walrus operator
    print(f"Too many items: {count}")

Why they ask: to check whether you keep your knowledge up to date.

Q25 Live coding: write a function that returns the most common words in a text.

First, I would clarify the requirements: whether the comparison should be case-insensitive and whether punctuation should be ignored. Assuming both, the approach is to convert the text to lowercase, extract the words with a regular expression, count them with collections.Counter and return the most frequent ones.

Solution:

import re
from collections import Counter

def top_words(text: str, n: int = 3) -> list[tuple[str, int]]:
    words = re.findall(r"[a-z']+", text.lower())
    return Counter(words).most_common(n)

print(top_words("The cat and the hat. The end!", 2))
# [('the', 3), ('cat', 1)]

re.findall() extracts all the words while ignoring punctuation, and `Counter` counts them in a single pass. most_common(n) returns the n most frequent words with their counts. The time complexity is O(n), where n is the length of the text.

For edge cases, an empty string returns an empty list. For very large files, I would read the file line by line and update the Counter incrementally, instead of loading the entire text into memory.

Why they ask: to evaluate your problem-solving approach, communication and knowledge of the standard library.


Tips for the Interview

Structure every answer. Start with a clear definition, explain the key difference or idea, then give a practical example. This structure works for almost every technical question.

Offer code, don't force it. After explaining a concept, it's fine to say "I can show a quick example if you'd like." Many interviewers will take you up on it, and it shows confidence.

Use examples from your own work. A short example from a project you have built, even a college or personal project, is more convincing than a definition alone.

Be honest when you don't know. Saying "I haven't worked with that yet, but my understanding is…" is much better than guessing. Interviewers value honesty and a logical approach.

Practise out loud. Speaking your answers is a different skill from reading them. A few minutes of daily practice makes a noticeable difference.

If you are still setting up Python on your laptop, the beginner-friendly Python setup guide for Windows 11 walks through it step by step.