Interview questions

Python Interview Questions

20 Python interview questions with model answers: data types, generators, decorators, the GIL, memory and coding tasks. For candidates and interviewers.

Python Interview Questions

What's here

20 Python interview questions, grouped into 4 areas: core language and data types, functions, iteration and idioms, objects and internals and practical coding and scenarios. Each one comes with why it is worth asking and what a strong answer contains, so the same question can be scored the same way by different interviewers.

  • Match the questions to the job: a data engineering role needs generators, memory and pandas depth, while a web role needs frameworks, testing and async.
  • Ask candidates to write a small piece of code (a decorator, a word counter) and talk through it; explanation shows more than the final code.
  • Follow every definition with 'when have you used that?' to separate real experience from memorised answers.
For hiring teams

Cohesyve finds, contacts and tests Python candidates on the real work, then ranks them for these interviews. 14-day free trial for 10 candidates, not charged until it ends.

Preparing for this interview yourself? Practise it free →

These Python interview questions cover what comes up in most Python programming interviews, whether the job is backend development, data engineering, automation or machine learning. They move from core data types to functions and idioms, then internals such as the GIL and memory management, and finish with practical coding scenarios. Candidates can use the 'what to look for' notes as model answers to check their own; interviewers can use them as a scoring guide and a prompt for follow-up questions.

Core Language and Data Types

The basics every Python developer should explain clearly, including the traps that catch people who learned the syntax without the semantics.

  1. 1

    What is the difference between a list and a tuple, and when would you use each?

    Why ask it

    A simple opener that quickly shows whether the candidate understands mutability and its consequences.

    What to look for

    Lists are mutable; tuples are immutable. Tuples suit fixed records of mixed types and can be dictionary keys or set members when their contents are hashable. A strong answer adds that the immutability is shallow: a tuple can hold a list, and that list can still change.
  2. 2

    Explain the difference between 'is' and '=='.

    Why ask it

    Confusing identity with equality causes subtle bugs.

    What to look for

    '==' compares values (it calls __eq__); 'is' checks whether two names point to the same object. Use 'is' for singletons such as None. Good candidates warn that small-integer and string caching are implementation details, so 'is' on numbers or strings should never be relied on.
  3. 3

    What goes wrong with a mutable default argument such as def add(item, items=[])?

    Why ask it

    A classic Python trap that separates people who have debugged real code from people who have only read tutorials.

    What to look for

    Default values are evaluated once, when the function is defined, so every call shares the same list and items pile up across calls. The fix is a None default and creating the list inside the function.
  4. 4

    How does Python pass arguments to functions?

    Why ask it

    Tests the mental model behind mutation bugs.

    What to look for

    Names are bound to objects and the function receives references to the same objects (often called pass by object reference or call by sharing). Mutating a passed list changes the caller's list; rebinding the parameter to a new object does not affect the caller.
  5. 5

    How do dictionaries work, and what can be used as a key?

    Why ask it

    Dicts are everywhere in Python; this checks depth beyond syntax.

    What to look for

    A hash table: keys are hashed for fast average-case lookup. Keys must be hashable, so immutable types such as strings, numbers and tuples of immutables work and lists do not. Dicts return keys in insertion order. Bonus: mentions defaultdict, Counter or dict comprehensions where they fit.
For hiring teams

Before the Python interviews, see who can do the work

Cohesyve finds and contacts Python candidates from your job description and tests each one on an AI job simulation of the role, so these questions go to a ranked shortlist. 14-day free trial for 10 candidates, not charged until it ends.

Functions, Iteration and Idioms

How well the candidate writes idiomatic Python rather than another language translated into Python syntax.

  1. 6

    What is a generator, and how is it different from returning a list?

    Why ask it

    Generators are central to memory-efficient Python.

    What to look for

    A function using 'yield' returns an iterator that produces values lazily, one at a time, keeping its state between calls. It uses little memory for large or infinite sequences but can only be iterated once. Generator expressions are the inline form.
  2. 7

    Explain decorators. How would you write one that logs how long a function takes?

    Why ask it

    Decorators appear in most frameworks; writing one shows comfort with functions as objects.

    What to look for

    A decorator takes a function and returns a wrapper, applied with @ syntax. The wrapper should accept *args and **kwargs, record a start time, call the original, log the elapsed time and return the result. Strong answers use functools.wraps to keep the original name and docstring.
  3. 8

    What do *args and **kwargs do?

    Why ask it

    Basic, but weak answers reveal shaky understanding of function signatures.

    What to look for

    *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. The same symbols unpack sequences and mappings at a call site. Good candidates mention keyword-only arguments after a bare *.
  4. 9

    What is a context manager, and when would you write your own?

    Why ask it

    Resource handling is a common source of leaks and bugs.

    What to look for

    An object used with 'with' that guarantees setup and cleanup, even if an exception occurs: files, locks, database transactions. Written either as a class with __enter__ and __exit__ or with contextlib.contextmanager and a single yield.
  5. 10

    When would you use a list comprehension, and when would you avoid one?

    Why ask it

    Shows judgement about readability, not only knowledge of syntax.

    What to look for

    Use them for simple transformations and filters that read in one line. Avoid them when logic needs several conditions or nested loops that hurt readability, or when the code exists only for side effects. For large data, a generator expression avoids building the whole list in memory.

Objects and Internals

Object-oriented Python and what happens under the hood. Expected for mid-level and senior roles.

  1. 11

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

    Why ask it

    Copy bugs are common with nested data structures.

    What to look for

    A shallow copy (copy.copy, list slicing, dict.copy) creates a new outer object but shares the inner objects; a deep copy (copy.deepcopy) recursively copies nested objects. Changing a nested list in a shallow copy changes the original too.
  2. 12

    What is the GIL, and how does it affect multithreaded Python?

    Why ask it

    Concurrency choices in Python depend on understanding the GIL.

    What to look for

    In the standard CPython build, the global interpreter lock lets only one thread execute Python bytecode at a time. Threads still help for I/O-bound work; CPU-bound work usually needs multiprocessing or native extensions. Up-to-date candidates mention that CPython has offered an optional free-threaded build with the GIL disabled since Python 3.13, and that libraries need to support it.
  3. 13

    What are dunder methods? Give a few examples you have implemented.

    Why ask it

    Shows whether the candidate understands Python's data model.

    What to look for

    Special methods such as __init__, __repr__, __str__, __eq__, __hash__, __len__ and __iter__ let classes work with built-in syntax and functions. Strong answers explain __repr__ (unambiguous, for developers) versus __str__ (readable, for users) and note that defining __eq__ affects hashing.
  4. 14

    How does Python manage memory?

    Why ask it

    Relevant for long-running services and data-heavy work.

    What to look for

    CPython uses reference counting, so objects are freed when their count drops to zero, plus a cyclic garbage collector for reference cycles. 'del' removes a name, not necessarily the object. Good answers mention tools such as tracemalloc for finding leaks.
  5. 15

    Do type hints change how Python runs your code?

    Why ask it

    Type hints are standard in modern codebases; this checks the candidate knows what they do and do not do.

    What to look for

    No. The Python runtime does not enforce annotations. They are used by type checkers, IDEs and linters, and some libraries read them to validate data. Good candidates explain how they use a type checker in CI and where they would still validate inputs at runtime.

Practical Coding and Scenarios

Short problems and real-world scenarios that show how the candidate writes and structures working code.

  1. 16

    Given a list of words, return the most common word. Talk me through your approach.

    Why ask it

    A small task that reveals fluency with the standard library and attention to edge cases.

    What to look for

    collections.Counter and most_common(1), or a dict count in one pass. Strong candidates ask about ties, case and punctuation, and an empty list, and state that the approach is linear in the number of words.
  2. 17

    A script that processes a large CSV file runs out of memory. What would you change?

    Why ask it

    Tests practical thinking about data size.

    What to look for

    Stream the file row by row with the csv module or generators instead of reading it all at once, process in chunks (for example pandas read_csv with chunksize), keep only the columns needed, and write results incrementally. Bonus for profiling before changing code.
  3. 18

    How do you handle exceptions well in Python?

    Why ask it

    Error handling shows maturity.

    What to look for

    Catch specific exceptions, never a bare except; keep try blocks small; use else for code that runs only on success and finally for cleanup; raise custom exceptions with 'raise ... from err' to keep the cause; log with context instead of swallowing errors.
  4. 19

    How do you structure and test a Python project?

    Why ask it

    Separates script writers from engineers who ship maintainable code.

    What to look for

    Virtual environments, dependencies declared in pyproject.toml or a lock file, a package layout with clear modules, pytest with fixtures and parametrised tests, mocking of external services, linting and type checks, all running in CI.
  5. 20

    When would you use asyncio rather than threads or multiprocessing?

    Why ask it

    Checks whether the candidate picks the right concurrency model.

    What to look for

    asyncio suits many concurrent I/O-bound tasks, such as thousands of network calls, using a single-threaded event loop with async and await. A blocking call inside a coroutine stalls everything, so blocking work goes to a thread pool. CPU-bound work belongs in processes.

Running the interview well

  • 1Match the questions to the job: a data engineering role needs generators, memory and pandas depth, while a web role needs frameworks, testing and async.
  • 2Ask candidates to write a small piece of code (a decorator, a word counter) and talk through it; explanation shows more than the final code.
  • 3Follow every definition with 'when have you used that?' to separate real experience from memorised answers.
  • 4Give a short piece of buggy code, such as a mutable default argument, and ask what it prints.
  • 5Let candidates look up exact function names; score reasoning and design choices, not recall of the standard library.
  • 6For senior roles, spend more time on project structure, testing, performance and code review than on syntax trivia.
  • 7Ask which Python version they use day to day and what changed recently; it shows whether they keep up.

Common questions

What Python topics come up most in interviews?

Data types and mutability, dictionaries, list comprehensions, generators, decorators, *args and **kwargs, exception handling, object-oriented basics and the GIL. Most interviews also include a short coding problem using lists, strings or dictionaries.

How should I prepare for a Python interview?

Practise explaining each concept out loud with a short example, write small programs without an IDE's autocomplete, and solve a range of list, string and dictionary problems. Review your own projects so you can explain design choices, testing and what you would change.

Are Python interview questions different for data roles and backend roles?

The core language questions are the same. Data roles add pandas, NumPy, memory handling for large datasets and sometimes SQL. Backend roles add web frameworks, APIs, databases, testing, async and deployment.

Do I need to know the latest Python version for an interview?

You should know the version your target team uses and be aware of notable recent changes, such as the optional free-threaded build available since Python 3.13. Interviewers rarely test release notes, but awareness shows you keep up.

What is the difference between Python 2 and Python 3?

Python 2 is no longer maintained, and modern code is written in Python 3. The question still comes up when a company has legacy code. Know the headline differences, such as print as a function and text strings being Unicode by default, and how you would approach a migration.

Is Python enough to get a developer job?

Python is a strong first language, but employers also expect related skills: Git, testing, SQL, an understanding of APIs, and the tools of your chosen field, such as a web framework or data libraries.

For hiring teams

Save these questions for the Python candidates who can do the work

Cohesyve takes your Python job description, finds candidates, reaches out to them and runs an AI job simulation of the real work, then returns a ranked shortlist.

1,500+

assessments completed

50%

faster time-to-hire

5 min

from JD to assessment

14-day free trial · 10 candidates · Not charged until the trial ends

For job seekers

Preparing for a Python interview yourself? Practise on an AI job simulation of the role. 3-day free trial, cancel anytime.

Practise a Python interview free →

See Cohesyve in action

Free 30-min walkthrough

See it on your role