Software

50 Most Common Python Interview Questions With Detailed Answers

Talha AslanTalha Aslan 19 min read 2 views

Python interview questions are short technical questions that test whether a candidate truly understands how the language behaves. In this guide I grouped the 50 questions I meet most often by topic. Each one gets a short, direct answer, and I added small code samples where they help. The goal is not a cheat sheet to memorise; it is the reasoning behind each answer.

I have managed web projects since 2012, and when I hire developers I ask many of these questions myself. If you care about the architecture side, read my guide to micro frontends. You can also browse the rest of the software category.

What are Python interview questions and what do they test?

Python interview questions are technical questions that probe the core behaviour of the language, from data types and object oriented programming to generators and concurrency. The interviewer uses them to check whether you can explain why code works the way it does, not whether you memorised syntax.

In my experience, Python interview questions come in three layers. First comes language knowledge: lists versus tuples, mutability, scope rules. Second comes design: decorators, context managers, class structure. Finally there is performance and concurrency. Therefore the groups below move from easy to hard. All answers target Python 3. For the official behaviour, always check the Python documentation.

Which basic Python interview questions come up first?

1. Is Python an interpreted language?

Partly. CPython first compiles source code to bytecode. Then a virtual machine runs that bytecode. So there is a compile step, but no compilation to machine code. Knowing this puts you one step ahead of the plain "it is interpreted" answer.

2. Is Python dynamically typed or strongly typed?

Both. The interpreter decides the type of a variable at runtime, which makes it dynamic. On the other hand, "3" + 3 raises an error because Python does not convert types silently. That makes it strongly typed.

3. What is PEP 8?

PEP 8 is the official style guide for Python code. It recommends four spaces for indentation, lowercase names with underscores for functions and CapWords for classes. In practice, knowing it tells the interviewer you will keep shared code readable.

4. Why does indentation matter in Python?

Python marks code blocks with indentation instead of curly braces. In other words, indentation is part of the syntax, not a visual choice. If you mix tabs and spaces in one block, you get a TabError.

What do interviewers ask about data types?

5. What are the built in data types?

For numbers you have int, float and complex. Text uses str and truth values use bool. For collections you use list, tuple, set and dict. In addition, None has its own type and represents the absence of a value.

6. What is the difference between is and ==?

== compares values, while is compares identity. In other words, is asks whether two names point to the same object in memory. That is why you write x is None for None checks.

a = [1, 2]
b = [1, 2]
print(a == b)  # True
print(a is b)  # False

7. Can a Python int overflow?

No. Because Python integers have arbitrary precision, they grow as long as memory allows. So you will not see the overflow errors you know from C or Java. However, this does not apply to float, because floating point numbers have a fixed size.

8. Why is 0.1 + 0.2 not exactly 0.3?

Because a float lives in binary, and 0.1 has no exact binary form. The result is 0.30000000000000004. For money, use the decimal module. For comparisons, use math.isclose.

How do lists, tuples, sets and dicts differ?

This group shows up in almost every interview. Start with the summary table:

TypeOrdered?Mutable?DuplicatesTypical use
listYesYesAllowedOrdered records
tupleYesNoAllowedFixed records, dict keys
setNoYesNoneDeduplication, membership tests
dictInsertion orderYesUnique keysFast lookup by key

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

A list is mutable and a tuple is not. As a result, a tuple can serve as a dict key and a list cannot. A tuple also uses slightly less memory, so it suits fixed records.

10. When should you use a set?

Use a set when you test membership often. An in check takes O(n) on average for a list and O(1) on average for a set. It is also the shortest way to drop duplicates.

11. Do dicts keep their order?

Yes. Since Python 3.7, insertion order is a language guarantee. Still, if your logic depends on order, say so in the code.

12. What makes a valid dict key?

The key must be hashable. That means its hash value never changes during its lifetime; strings, numbers and tuples of hashable items qualify.

Why do mutability questions come up so often?

13. What do mutable and immutable mean?

You can change a mutable object in place; lists, dicts and sets work this way. With an immutable object, every change creates a new object; strings, ints and tuples belong here. This split explains most surprises when you pass arguments to functions.

14. Why is a list default argument dangerous?

Python creates the default value once, when it defines the function. Every call then shares the same list. The safe pattern uses None:

def add(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

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

A shallow copy duplicates only the outer container, so the inner objects stay shared. A deep copy rebuilds every nested object. For example, copy.copy is not enough for nested lists; you need copy.deepcopy. I usually ask this together with question 14, because both test the same mental model.

What do interviewers ask about functions and arguments?

16. What do *args and **kwargs do?

*args collects extra positional arguments into a tuple. **kwargs collects keyword arguments into a dict. Put simply, together they let you write functions with flexible signatures.

def summary(*args, **kwargs):
    print(args)    # (1, 2)
    print(kwargs)  # {'name': 'Ali'}

summary(1, 2, name="Ali")

17. Does Python pass arguments by value or by reference?

Neither, strictly speaking. Python uses "pass by object reference". The function receives a copy of the reference to the object. So if you mutate a list inside the function, the caller sees the change. If you rebind the name to a new object, the caller does not.

18. Are functions first class objects?

Yes. You can assign a function to a variable, pass it to another function and return it from a function. In fact, decorators rely on exactly this feature, so expect a follow up.

19. Does Python enforce type hints at runtime?

No. The interpreter ignores type hints at runtime; they exist for documentation and static analysis. If you want checks, run a tool such as mypy. Still, hints make large codebases much easier to read.

How should you answer lambda and comprehension questions?

20. What is a lambda function?

A lambda is an anonymous function made of a single expression. You mostly use it to pass a short key to functions such as sorted or max. If you need more than one line, a regular def reads better.

people = [("Ayse", 31), ("Can", 25)]
print(sorted(people, key=lambda p: p[1]))

21. How does a list comprehension differ from a for loop?

A comprehension does the same job in one line and is often faster. That said, a comprehension with three nested conditions becomes unreadable. At that point, go back to a plain loop.

22. How do you choose between map, filter and a comprehension?

If you apply an existing function, map is short and clear. If you combine a condition and a transformation, a comprehension reads better. In short, the rule is readability, not speed.

How do scope, closures and name lookup work?

23. What is the LEGB rule?

LEGB is the order Python follows when it looks up a name: Local, Enclosing, Global, Built in. The interpreter checks the local scope first, then the enclosing function, then the module level and finally the built in names. Then it stops at the first match.

24. What do global and nonlocal do?

global lets a function rebind a module level name. nonlocal lets a nested function write to a variable of the enclosing function. Use both sparingly, because hidden state makes debugging harder.

25. What is a closure?

A closure is an inner function that remembers variables from the scope where you defined it. Even after the outer function returns, the inner one keeps access to those values.

def multiplier(n):
    def multiply(x):
        return x * n
    return multiply

double = multiplier(2)
print(double(5))  # 10

How do you prepare for object oriented programming questions?

In OOP rounds the interviewer often probes inheritance versus composition too. My short answer: use inheritance for an "is a" relationship and composition for a "has a" relationship.

26. What is the difference between __init__ and __new__?

__new__ creates the object and __init__ initialises it. In daily work you almost always write __init__. You need __new__ mainly when you subclass immutable types or build special patterns such as a singleton.

27. What is self and why do you write it explicitly?

self is the instance that calls the method. Python asks for it as an explicit parameter instead of hiding it, in line with the idea that explicit beats implicit. You could pick another name, but the community standard is self.

28. How do classmethod and staticmethod differ?

A classmethod receives the class as its first argument, which makes it ideal for alternative constructors. A staticmethod receives neither the class nor the instance. It is a plain function that belongs to the class logically.

29. What is the MRO?

The MRO, or method resolution order, decides which class supplies a method under multiple inheritance. Python computes it with the C3 linearisation algorithm. To see it, print MyClass.__mro__. Also, every super() call follows this order.

Why do dunder methods and the data model matter?

30. What is the difference between __str__ and __repr__?

__str__ produces readable output for users. __repr__ produces an unambiguous representation for developers. A good __repr__ shows code that could rebuild the object. If you write only one, write __repr__, because Python falls back to it when __str__ is missing.

31. What happens to __hash__ when you define __eq__?

If a class defines __eq__ but not __hash__, Python sets __hash__ to None. As a result, your objects can no longer go into a set or serve as dict keys. Remember the rule: equal objects must have equal hashes.

32. What does a dataclass do?

@dataclass generates __init__, __repr__ and __eq__ from field definitions. As a result, it removes a lot of boilerplate in classes that mainly carry data.

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: int
    y: int

Here frozen=True makes the object immutable and hashable. For the full details, the official data model reference is the best source.

What do iterator and generator questions test?

33. How does an iterable differ from an iterator?

An iterable is anything you can loop over; it has an __iter__ method. An iterator returns the next item through __next__ and remembers its position. A list is iterable but not an iterator; iter(my_list) gives you one.

34. What is a generator and why does it save memory?

A generator is a function that uses yield and produces values one at a time, on demand. Because of that, it never holds the full result in memory. That is why you can process a file with millions of lines comfortably.

def lines(path):
    with open(path) as f:
        for line in f:
            yield line.strip()

35. What does yield from do?

yield from hands out every value of another iterable in turn. It removes the need for a manual loop in chains of generators. Moreover, it captures the return value of the sub generator.

How do you explain decorators and context managers?

36. What is a decorator?

A decorator is a function that takes another function, changes its behaviour and returns it. For example, it suits cross cutting jobs such as logging, timing and permission checks.

import functools, time

def timed(fn):
    @functools.wraps(fn)
    def wrapper(*a, **k):
        t = time.perf_counter()
        result = fn(*a, **k)
        print(fn.__name__, time.perf_counter() - t)
        return result
    return wrapper

37. Why do you need functools.wraps?

Without it, the wrapper hides the name and docstring of the original function. wraps copies that metadata across. Therefore debuggers and documentation tools see the right name.

38. What is a context manager?

A context manager defines code that runs when you enter and leave a with block. Above all, it guarantees cleanup, such as closing a file or releasing a lock, even when an error occurs. You can write one with __enter__ and __exit__, or with contextlib.contextmanager.

Which error handling questions should you expect?

39. How do try, except, else and finally work together?

try holds the risky code and except catches the error. else runs only when no error occurred. finally runs in every case. I use else to keep success code out of the try block, so I do not catch the wrong exception by accident.

try:
    number = int(raw)
except ValueError:
    print("Not a number")
else:
    print(number * 2)
finally:
    print("Done")

40. Why is a bare except a bad habit?

A bare except: catches everything, including KeyboardInterrupt and SystemExit. As a result, you cannot stop the program cleanly, and you hide the real bug. Instead, name the exception you expect. If needed, define your own exception class.

What should you know about the GIL and concurrency?

41. What is the GIL?

The GIL, or Global Interpreter Lock, lets only one thread execute Python bytecode at a time in CPython. On the plus side, it simplifies memory management. However, it stops CPU heavy threads from running in parallel. The Python glossary defines it clearly.

42. How do you choose between threading, multiprocessing and asyncio?

For I/O bound work such as network calls or disk reads, threading or asyncio is enough. The GIL releases while a thread waits. For CPU bound work, use multiprocessing, because each process has its own interpreter and its own GIL. Asyncio is the lightest option for thousands of concurrent connections on one thread.

43. Is the GIL going away?

Partly. Through PEP 703, Python 3.13 introduced an experimental free threaded build without the GIL. Still, the default CPython build keeps the GIL, and many C extensions are still catching up. Knowing this shows you follow the language, but it is too early to base production decisions on it.

A common follow up question asks why threads still help despite the GIL. The answer is simple: the lock releases during network and disk waits, so those waits overlap.

What do interviewers ask about modules, packages and virtual environments?

44. What does if __name__ == "__main__" do?

When you run a file directly, __name__ equals "__main__". When another file imports it, __name__ holds the module name instead. In practice, this check keeps test or command line code from running on import.

45. Why use a virtual environment?

A virtual environment keeps the dependencies of each project in a separate folder. So one project can use Django 4 while another uses Django 5 without conflicts. The venv module in the standard library covers this.

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

What do they ask about testing and code quality?

Testing questions often turn into a practical task: "Which tests would you write for this function?" A strong answer covers more than the happy path. It also covers empty input, wrong types and boundary values. So prepare at least three test ideas for every sample you write.

46. How do unittest and pytest differ?

unittest ships with the standard library and uses a class based structure. pytest is a third party package, but plain assert statements, fixtures and a rich plugin ecosystem mean you write less code. Most teams I work with prefer pytest today. Also, pytest can run existing unittest suites.

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5

47. When do you need a mock?

If the code under test talks to a payment service, a database or an external API, you do not want real calls in your tests. unittest.mock swaps that dependency for a fake object. It also lets you check that your code made the call with the right parameters. As a result, tests stay fast and repeatable.

How do you answer performance and memory questions?

48. How does garbage collection work in Python?

CPython relies mainly on reference counting. When no reference to an object remains, Python frees it right away. However, reference counting cannot catch reference cycles. So a generational garbage collector runs on top. You can inspect it with the gc module.

49. How do you speed up slow Python code?

Measure first, then fix. Profiling often surprises you compared with guessing. This is the order I follow:

  1. Find the slowest function with cProfile.
  2. Review the algorithm and data structure; use a set instead of searching a list.
  3. Cache repeated work with functools.lru_cache.
  4. Move numeric work to vectorised libraries such as NumPy.
  5. If needed, push the bottleneck into a C extension or a separate process.

50. What does __slots__ do?

__slots__ fixes the attributes an instance may have and removes the per instance __dict__. When you create millions of small objects, it cuts memory use noticeably. On the other hand, you can no longer add new attributes to an instance later.

How should you study Python interview questions?

Instead of memorising, try every question on your own machine. For example, do not just read question 14; reproduce the default list bug yourself. That experience turns into a far more convincing answer. Also, structure each answer as "what, why, when". This shows the interviewer how you think.

Here is the preparation plan I recommend:

  • Week one: data types, scope and functions, all tested in code.
  • Then, in week two, build a small project that uses OOP, decorators and generators.
  • In week three, focus on concurrency and performance questions.
  • Week four: practise answering out loud and aim to finish each answer in two minutes.

Choose your sources with care. The tutorial in the official documentation teaches the basics in the right order. Small exercise sites help with algorithm practice. Still, try to explain every solution you see there in your own words. For instance, after you solve a generator task, say out loud how memory would change if you used a list instead.

I also suggest a simple notes habit. Each day, write down one concept you got wrong in a single sentence. After four weeks you have a short list of your own weak spots. On the morning of the interview, that list is all you need to review.

These timings are a starting point based on my field experience, not a guarantee. Shorten or stretch them to match your background.

Which mistakes do candidates make most often in the interview?

The mistake I see most in my own interviews: candidates know the right answer but cannot explain the reason. Saying "tuples are immutable" is not enough. You should also say why that makes them work as dict keys. The second common mistake is guessing on an unknown question and then defending the wrong answer. If you do not know, say so and explain how you would find out.

Other frequent mistakes include:

  • Coding in silence and leaving the interviewer guessing.
  • Never asking about edge cases such as an empty list or None input.
  • Skipping complexity analysis and never mentioning O(n) versus O(n²).
  • Writing unreadable code with names that ignore PEP 8.

One last tip: do not hesitate to ask the interviewer questions. Ask about input size, expected performance or what should happen on error. Those questions show how you would behave on a real project. They also buy you a few seconds to think.

In short, the interviewer is not looking for a perfect encyclopaedia. They want someone they can work with, who explains ideas clearly.

Where does Python help in real web projects?

Python is not only a data science language, and many Python interview questions reflect that. In my projects it shows up most in automation and reporting. For example, during a site migration a script that checks hundreds of redirects turns days of manual work into minutes. You can also verify single URLs with the redirect checker.

Likewise, you can write small Python tools that measure site speed on a schedule and log the results. I explain how speed affects search visibility in my article on site speed and SEO. The measuring method is in my Lighthouse guide. Crawling scripts also work well for automating technical SEO checks.

Another example comes from content work. A simple script that checks title and description length across hundreds of pages speeds up quality control before launch. For a single page, the word counter is enough; bulk work needs a language like Python. In short, what you learn for the interview pays off in daily work too.

What should you do after these Python interview questions?

If you can answer these 50 questions comfortably, you are ready for junior and mid level interviews. After that, the next step is to show that knowledge in a real project. A small but clean GitHub project says more than a long list of certificates. So take care with the README, the tests and the code layout.

If you are hiring developers or planning a web project with a Python backend, we can clarify the technical needs together. See how I work on the web design service page, or write to me directly through the contact page.

Frequently Asked Questions

How long does it take to prepare for a Python interview?
If you already know the basics, four weeks is usually a reasonable start. Spend the first two weeks on language fundamentals and OOP, the third on concurrency and performance, and the last on practising answers out loud. This is a suggestion based on my field experience, not a guarantee; your background can make it shorter or longer.
Do Python interviews include a coding test?
Most companies include one. It usually comes as a live task in a shared editor or a small take home assignment. Besides a correct result, the interviewer watches for readable names, edge case handling and a comment on complexity. Thinking out loud while you code leaves a better impression than silently typing the right solution.
Are junior and senior Python interview questions different?
Yes, clearly. Junior interviews focus on data types, functions and basic OOP. Senior interviews move to the GIL, concurrency, memory management, architecture decisions and testing strategy. Senior candidates are also expected to walk through a hard technical decision from a past project and explain the trade offs behind it.
Do interviewers still ask about Python 2?
Rarely. Official support for Python 2 ended on 1 January 2020, so almost every new project runs on Python 3. Teams that still migrate an old codebase may ask about differences such as the print statement or integer division. Otherwise, you can build your preparation entirely on Python 3 and its current features.
What should I do if I do not know the answer?
Stay calm and say honestly that you do not know. Then start from the closest concept you do know and explain how you would reason about it. Mention that you would check the documentation or test a small snippet. Interviewers prefer a clear thought process over a confident defence of a wrong answer.
#Python#interview#developer career#OOP#generators#decorators#GIL
Share:
Talha Aslan
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Let's talk about your project.

No middlemen, no layers: you talk directly to the expert doing the work. The first consultation is free, I listen to your goal and come back with a clear roadmap.

WhatsApp Call Now