Python interview questions

46 questions, easy to hard. Read one, then answer it out loud: an AI interviewer follows up, hints when you're stuck and grades your answer.

Python interviews check that you understand the language, not just its syntax: mutability, closures, classes, generators, error handling and concurrency.

Core Types

  1. In Python, a function that appends to a list passed in changes the caller's list, but a function that adds one to a number doesn't change the caller's number. Explain mutability and how it explains the difference.

    What a strong answer covers
    • Which kinds of Python object can change in place and which can't.
    • What really happens to an object when you pass it to a function.
    • Why the two examples behave differently, step by step.
    • How to protect a caller's data when that matters.

    Common mistake: Saying Python passes lists "by reference" and numbers "by value": both are passed the same way.

  2. You need to store a sequence of to-do items, a pair of map coordinates, the unique tags on a post, and a lookup from username to email address. Explain which Python collection fits each and why.

    What a strong answer covers
    • How the four built-in collections differ in order, change and uniqueness.
    • Matching each piece of data to the collection whose strengths it needs.
    • Why immutability matters beyond safety, such as for lookups.
    • A short reason for every choice, not just its name.

    Common mistake: Picking a list for everything because it works, without saying what the other collections would give you.

  3. A colleague compares strings with the is operator and it usually works, then fails in production. Explain the difference between the is operator and the double equals operator, and when to use each.

    What a strong answer covers
    • The difference between two values being equal and two names pointing at one object.
    • Why the bug can stay hidden in testing and show up later.
    • Which comparison suits everyday values and which suits special one-of-a-kind objects.

    Common mistake: Treating the occasional success as proof the code is fine, when it rests on an interpreter detail.

  4. A function checks whether a discount was given with a simple if on the value, and it wrongly treats a discount of zero as missing. Explain truthiness in Python and how to write the check correctly.

    What a strong answer covers
    • Which values Python counts as false in a condition.
    • How that rule causes this particular bug.
    • A clearer way to test for a missing value.
    • When leaning on truthiness is still good, idiomatic Python.

    Common mistake: Banning truthiness checks altogether instead of recognising the cases where zero or empty is a real value.

  5. A function takes an optional list that defaults to an empty list, and appends to it. Each call seems to remember items from earlier calls. Explain why, and the idiomatic fix.

    What a strong answer covers
    • When Python actually creates a default value.
    • Why calls end up sharing state they shouldn't.
    • The standard pattern for an optional collection argument.
    • Which other kinds of default can cause the same trouble.

    Common mistake: Blaming a stray global or caching layer instead of seeing that the default object itself is being reused.

  6. You build a three-by-three grid by multiplying a list containing one row of three zeros by three, and setting one cell changes a whole column. Explain why, and how copying works in Python.

    What a strong answer covers
    • Why repeating a list of lists produces linked rows.
    • A safe way to build a grid of independent rows.
    • What a shallow copy duplicates and what it still shares.
    • When a full recursive copy is worth its cost.

    Common mistake: Assuming any copy of the outer list also copies everything nested inside it.

  7. You try to use a list of coordinates as a dictionary key and Python raises an error saying the type is unhashable. Explain what hashable means, why dictionary keys must be hashable, and how to fix this.

    What a strong answer covers
    • How dictionaries and sets locate entries so quickly.
    • Why a key must stay unchanged while it's stored.
    • Immutable alternatives that work as keys.
    • What your own classes need to work as keys.

    Common mistake: Converting the key to a string to silence the error, which hides the real rule and invites clashes.

Functions and Closures

  1. A colleague writes a loop that starts with an empty list, goes through orders, and appends the total of each paid order. Explain how a list comprehension could replace it, and when a comprehension stops being a good idea.

    What a strong answer covers
    • The parts of a comprehension and how they map onto the loop.
    • Reading the rewritten version aloud in plain words.
    • The related forms for other collections and for lazy results.
    • Where readability says a plain loop is better.

    Common mistake: Squeezing complicated or side-effecting logic into one long comprehension just because it's possible.

  2. Explain the different ways to pass arguments to a Python function, including positional, keyword and default arguments, and what star args and double-star kwargs collect.

    What a strong answer covers
    • How Python matches the values you pass to the parameters a function declares.
    • How defaults make parameters optional.
    • What the single-star and double-star parameters gather, and in what type.
    • Ways to force callers to name an argument, or to spread a collection into a call.

    Common mistake: Mixing up which star collects which kind of argument, or what type each one ends up as.

  3. You have a list of employee records and need them sorted by department, then by salary from highest to lowest. Explain how sorting with a key function works in Python and how you'd do this.

    What a strong answer covers
    • How a key function changes what sorting compares.
    • Concise ways to write a key.
    • Sorting by more than one field with mixed directions.
    • The difference between sorting in place and returning a new list.

    Common mistake: Assigning the result of the in-place sort to a variable and getting nothing back.

  4. A function reads a module-level counter fine, but as soon as it adds one to the counter, Python raises an unbound local error. Explain Python's scope rules and why this happens.

    What a strong answer covers
    • The order in which Python searches for a name.
    • How a single assignment changes a name's scope for the whole function.
    • The keywords that let a function rebind outer names.
    • A design that avoids shared global state.

    Common mistake: Thinking the variable becomes local only from the line of the assignment onwards.

  5. Explain what a closure is in Python, using the example of a function that makes multiplier functions, such as one that doubles and one that triples.

    What a strong answer covers
    • What it means for an inner function to remember its surroundings.
    • How the multiplier example produces functions that each keep their own factor.
    • What changes when the inner function needs to update a remembered value.
    • Where closures turn up in real code and what can replace them.

    Common mistake: Describing a closure as any nested function, without saying what it keeps alive after the outer function returns.

  6. You want to log how long several functions take without editing each one's body. Explain what a decorator is and how you'd write a timing decorator.

    What a strong answer covers
    • What a decorator takes and gives back, and when it's applied.
    • How a timing wrapper passes calls through untouched.
    • Keeping the wrapped function's identity for debugging and docs.
    • Decorators that need their own settings.

    Common mistake: Forgetting to return the original function's result, so every decorated function suddenly returns None.

  7. A loop creates five small functions, each meant to return its own loop number, but calling them all returns four. Explain why Python closures behave like this and how to fix it.

    What a strong answer covers
    • When a closure looks up the variables it uses.
    • Why every function in the loop ends up seeing the same final value.
    • Ways to capture the value at the moment each function is created.
    • Other places the same surprise appears.

    Common mistake: Assuming each loop iteration gets its own fresh copy of the loop variable, as in some other languages.

Classes and Objects

  1. A newcomer to Python asks what the init method and the self parameter are for in a class. Explain how a class, its instances and these two pieces fit together, using a bank account as an example.

    What a strong answer covers
    • The difference between a class and the objects made from it.
    • What runs when a new object is created, and what it sets up.
    • How methods know which object they're working on.
    • Data that belongs to one object versus data shared by all of them.

    Common mistake: Calling the init method a constructor that creates the object, when the object already exists and init only sets it up.

  2. Your codebase has dozens of small classes that just store fields and have long, repetitive init methods. Explain what dataclasses are and how they'd help.

    What a strong answer covers
    • Which repetitive methods a dataclass writes for you.
    • Setting defaults safely, including for collections.
    • Options for read-only or orderable records.
    • When a different tool fits better, such as for validating outside data.

    Common mistake: Giving a field a plain empty list as its default and expecting the same safety as anywhere else.

  3. You've written a Money class and want instances to print nicely, compare with double equals, add together with the plus sign, and work with the len function where it makes sense. Explain Python's special methods, sometimes called dunder methods, and which ones you'd implement.

    What a strong answer covers
    • How classes hook into Python's built-in syntax and functions.
    • Which methods give readable output and value-based comparison.
    • Supporting the plus operator and refusing combinations that make no sense.
    • Judging which hooks a money type should and shouldn't have.

    Common mistake: Raising a generic error or guessing when adding unsupported types, instead of letting Python try the other operand.

  4. A colleague coming from Java has written get and set methods for every attribute of a Python class. Explain why that's unusual in Python and how properties let you add logic later without changing callers.

    What a strong answer covers
    • Why plain attributes are the Python norm.
    • How a property makes a method read like an attribute.
    • Typical reasons to add logic behind an attribute.
    • Why you can change your mind later without breaking callers.

    Common mistake: Keeping Java-style getters and setters just in case, when Python already lets you add logic later for free.

  5. Explain the difference between an ordinary method, a class method and a static method in Python, and give a realistic use for a class method.

    What a strong answer covers
    • What each kind of method receives automatically.
    • A realistic job that suits a class method.
    • What a static method is, and isn't, for.
    • How these choices behave once subclasses get involved.

    Common mistake: Treating class methods and static methods as interchangeable, which breaks alternative constructors in subclasses.

  6. A subclass overrides the init method and suddenly the parent's attributes are missing. Explain how inheritance works in Python, what super does, and how method resolution order matters with multiple inheritance.

    What a strong answer covers
    • What a subclass inherits and what overriding replaces.
    • How to make sure the parent's set-up still runs.
    • How Python picks a method when there are several parents.
    • When composition beats a deep class hierarchy.

    Common mistake: Describing super as simply calling the direct parent, which isn't true with multiple inheritance.

  7. A function accepts anything with a read method, and your team wants type hints without forcing every caller to inherit from a base class. Explain duck typing, abstract base classes and typing protocols, and when you'd use each.

    What a strong answer covers
    • How Python decides whether an object is usable.
    • The trade-offs of interfaces that require inheritance.
    • How a type checker can accept any object with the right shape.
    • Choosing between the approaches for a given design.

    Common mistake: Assuming type hints need a shared base class, so every caller has to inherit from something.

Iterators and Generators

  1. Explain what Python actually does behind the scenes when you loop over a list with a for loop, and what makes something iterable.

    What a strong answer covers
    • The protocol a for loop follows behind the scenes.
    • How a loop knows when to stop.
    • The difference between something you can loop over and the thing doing the looping.
    • Why some objects can be looped over only once.

    Common mistake: Saying a for loop works by counting indexes, which isn't how Python iterates.

  2. You need to process a log file far too large to fit in memory, line by line, keeping only the error lines. Explain what a generator function is and how you'd use one here.

    What a strong answer covers
    • What makes a function a generator and how it pauses and resumes.
    • Why the approach keeps memory use low for huge files.
    • Sketching the filtering solution in words.
    • Limits of generators and a shorter form for simple cases.

    Common mistake: Reading every line into a list first and then filtering it, which defeats the point on a file too big for memory.

  3. Code calls map on a list of records, then checks the length of the result and later loops over it twice, and both steps misbehave. Explain why, and how to work with lazy iterators safely.

    What a strong answer covers
    • Which built-in functions hand back lazy results rather than lists.
    • Why both symptoms in the scenario happen.
    • When to make the result concrete and when to keep it lazy.

    Common mistake: Assuming map gives back a list, as it did in older versions of Python.

  4. Explain what Python's with statement does, why it's the right way to open files and locks, and how you'd write your own context manager for timing a block of code.

    What a strong answer covers
    • What the with statement guarantees, even when errors occur.
    • The protocol behind it.
    • A quick way to write your own with a decorator.
    • Uses beyond files.

    Common mistake: Writing the clean-up after a yield without protecting it, so it's skipped when the block raises.

  5. Explain what the itertools module offers and how you'd use it to process records in batches of one hundred, group consecutive records by day, and chain several sources into one stream.

    What a strong answer covers
    • What kind of tools itertools provides and why they're efficient.
    • How you'd split a stream into fixed-size batches.
    • Grouping consecutive items, and the condition that makes it correct.
    • Joining several sources into one stream, plus a few other handy tools.

    Common mistake: Using groupby on unsorted data and being surprised by the same key appearing in several groups.

  6. You must read millions of rows from a CSV file, parse them, drop invalid ones, enrich each with a lookup, and write the results in batches to a database. Explain how you'd structure this as a pipeline of generators and why.

    What a strong answer covers
    • How to split the job into small connected stages.
    • Why memory stays flat no matter how big the file is.
    • The testing and reuse benefits of small stages.
    • Practical concerns such as writes, bad rows and resource clean-up.

    Common mistake: Building one giant function, or collecting each stage into a list, so memory grows with the input.

Errors and Tooling

  1. A script wraps its whole body in a try block with a bare except that prints something went wrong. Explain how exception handling works in Python and how you'd improve this.

    What a strong answer covers
    • The roles of the blocks in a try statement.
    • What a catch-all handler hides.
    • How to narrow handling to what you expect.
    • Keeping enough detail to diagnose unexpected failures.

    Common mistake: Replacing the bare except with a catch for every exception type, which hides bugs in exactly the same way.

  2. Two of your Python projects need different versions of the same library, and installing one breaks the other. Explain what virtual environments are and how you'd manage dependencies per project.

    What a strong answer covers
    • What a virtual environment isolates and why.
    • The everyday workflow for each project.
    • Making installs reproducible for teammates and servers.
    • Tools that help, and what not to commit.

    Common mistake: Installing everything into the system Python and hoping project versions never clash.

  3. Type Hints
    • easy
    • Pro

    Your team is debating whether to add type hints to a growing Python codebase. Explain what type hints are, what they do and don't do at runtime, and how you'd introduce them.

    What a strong answer covers
    • What type hints describe.
    • What happens to them when the program actually runs.
    • The practical benefits for a team.
    • A sensible way to adopt them gradually.

    Common mistake: Believing type hints make Python check types at runtime, so wrong values will be rejected automatically.

  4. Your payment library returns error strings like card declined, which callers compare with text. Explain how you'd design custom exceptions instead and how callers would use them.

    What a strong answer covers
    • A small hierarchy of exceptions for the library.
    • How callers handle broad or specific failures.
    • Carrying useful details with the error.
    • Keeping the original cause when wrapping errors.

    Common mistake: Creating one generic exception and putting the reason in the message, which leaves callers comparing text again.

  5. Python developers often say it's easier to ask forgiveness than permission. Explain what this means compared with look before you leap, with an example, and when each style is better.

    What a strong answer covers
    • The two styles and how each handles a possible failure.
    • A concrete case where checking first is unreliable.
    • When checking first is still the clearer choice.
    • Built-in shortcuts that avoid the dilemma.

    Common mistake: Claiming one style is always right, rather than weighing how often failure happens and whether things can change in between.

  6. Your team has no tests for a Python service. Explain how you'd start with pytest, including how tests are found, how fixtures work, and how to test many inputs without copying code.

    What a strong answer covers
    • How pytest discovers tests and reports failures.
    • Sharing set-up and clean-up between tests.
    • Running one test over many cases.
    • Isolating outside services and running the suite automatically.

    Common mistake: Copying the same test many times with small changes instead of letting pytest run one test over many inputs.

  7. You want to share an internal Python library across several services instead of copying the code. Explain how you'd package it.

    What a strong answer covers
    • The file that describes the package and how it's built.
    • A tidy layout and the artefact you produce.
    • How services get and install the shared library.
    • Versioning and dependency ranges that avoid conflicts.

    Common mistake: Pinning exact dependency versions inside the library, so it clashes with the services that install it.

Concurrency and Async

  1. You have two slow Python scripts: one downloads thousands of web pages, the other resizes thousands of images. Explain when to use threads, processes or asyncio, and which fits each script.

    What a strong answer covers
    • How to tell work that waits from work that computes.
    • Which tool suits each script and why.
    • The interpreter limit that drives the choice.

    Common mistake: Reaching for threads for both scripts, expecting the image work to speed up too.

  2. You need to run the same function over a thousand items, either waiting on the network or crunching numbers. Explain how Python's concurrent futures module helps, the difference between its thread pool and process pool executors, and how you collect the results.

    What a strong answer covers
    • What an executor manages for you.
    • Choosing between the two pool types.
    • The ways to collect results and errors.
    • Shutting the pool down tidily and sizing it sensibly.

    Common mistake: Assuming an error in a worker will stop the program on its own, when it only shows up once you ask for that result.

  3. A colleague added threads to a number-crunching Python function and it got no faster. Explain what the global interpreter lock is, why it exists, and how to work around it.

    What a strong answer covers
    • What the lock restricts and in which interpreter.
    • Why it was introduced.
    • When threads still help despite it.
    • Ways to get real parallel speed-ups, including newer developments.

    Common mistake: Saying Python can't do parallel work at all, when processes and many libraries get around the lock.

  4. In a code review you spot four threads that each add one to a shared counter with counter plus-equals one, and no lock. The author says the global interpreter lock makes this safe. Explain why it isn't, and how to fix it.

    What a strong answer covers
    • Why a simple increment isn't one indivisible step.
    • What the interpreter lock does and doesn't guarantee.
    • How to make the update safe.
    • Designs that avoid shared counters or keep locking cheap.

    Common mistake: Trusting the interpreter lock to protect shared data, so missing updates only appear under heavy load.

  5. One thread reads lines from a huge log file and several worker threads parse them. Explain how to connect them with Python's queue module, how to stop memory filling up if the reader is faster than the workers, and how to shut the workers down cleanly at the end.

    What a strong answer covers
    • A safe way to hand work from one thread to others.
    • How idle workers wait without wasting CPU.
    • Stopping a fast reader from filling up memory.
    • A reliable way to tell workers there's no more work.

    Common mistake: Waiting for the queue to empty and assuming the workers will exit, when they're still blocked waiting for more.

  6. You move a slow function onto a process pool and hit three problems: passing a lambda fails with a pickling error, a global list the workers append to stays empty in the main program, and on Windows the script fails with an error about starting a new process before the current one has finished bootstrapping. Explain each problem and its fix.

    What a strong answer covers
    • How data travels between processes and what that rules out.
    • Why changes made in workers don't come back by themselves.
    • What the start method means for how the script is laid out.
    • The cost of moving data, and how to keep it down.

    Common mistake: Expecting processes to share variables the way threads do.

  7. Explain how async and await work in Python's asyncio, what the event loop does, and why calling an async function without awaiting it does nothing useful.

    What a strong answer covers
    • What calling an async function actually gives you.
    • How the event loop decides what runs next.
    • The kind of concurrency this provides, and what it doesn't.
    • How Python flags a coroutine that never ran, and how to start the program.

    Common mistake: Thinking asyncio runs code in parallel on several cores.

  8. Your async code fetches fifty URLs by awaiting each one in turn inside a loop, and it's as slow as synchronous code. Explain why, and how to run them concurrently without overwhelming the server.

    What a strong answer covers
    • Why the loop is no faster than ordinary synchronous code.
    • Starting many requests together.
    • Capping how many run at once.
    • Dealing with failures and slow responses.

    Common mistake: Firing all fifty requests at once with no limit and overloading the server or getting rate-limited.

  9. Your asyncio service calls a slow payment provider. Explain how to put a time limit on the call, what actually happens inside a coroutine when it's cancelled, and the mistake that stops cancellation from working.

    What a strong answer covers
    • Ways to put a time limit on an awaited call.
    • How cancellation reaches a coroutine, and where it can't.
    • The handling mistake that quietly breaks cancellation.
    • Cleaning up and deciding what happens after a timeout.

    Common mistake: Swallowing the cancellation with a catch-all handler, such as a bare except, and carrying on, so the task can no longer be stopped.

  10. Your asyncio web service becomes unresponsive under load, and you find it uses an ordinary synchronous HTTP library and a CPU-heavy report function inside async handlers. Explain the problem and how to fix it.

    What a strong answer covers
    • Why one blocking call stalls every request.
    • Replacing blocking input and output with async-friendly libraries.
    • Where to send work that can't avoid blocking.
    • How to spot the problem in a running service.

    Common mistake: Marking a function async and assuming that makes the slow calls inside it non-blocking.

  11. Your asyncio app sends audit logs in the background by calling create task and never keeping the task it returns, so requests aren't slowed down. Some audit logs never arrive, and the failures leave no clear error. Explain two reasons this can happen, and how to fix it.

    What a strong answer covers
    • What the event loop does, and doesn't, hold on to.
    • Where errors go in a task nobody waits for.
    • A pattern for fire-and-forget work that's actually safe.
    • Sturdier options for work that must not be lost.

    Common mistake: Assuming a background task will run to completion and report its errors just because it was started.

  12. A Flask app counts requests and caches user settings in module-level dictionaries. It works on a laptop, but in production behind Gunicorn with four worker processes, the request count jumps around and users sometimes see their old settings after saving. Explain why, and how to fix it.

    What a strong answer covers
    • How a multi-process server treats module-level variables.
    • Why each symptom in the scenario follows from that.
    • Where shared state should live instead.
    • The trade-offs of moving it, and when local caching is still fine.

    Common mistake: Adding a thread lock around the dictionaries, which can't help because the workers are separate processes.

Questions about practising

How should I prepare for python interview questions?
Practise answering them out loud, not just reading them. Explaining an answer under follow-up questions is what interviews test. Work through the 46 questions here from easy to hard, and revisit the ones you struggle with.
Can I practise python interview questions with an AI?
Yes. Open any question and start a voice session: an AI interviewer asks it, follows up on your answer, gives hints when you're stuck and grades your answer with written feedback when the call ends.
Are these python interview questions free?
5 of the 46 questions are free to practise. Sign in with Google, no card needed. Pro unlocks the rest, plus practice calls to your phone.