Python Interview Questions
2026 Edition
From list-vs-tuple to the GIL and Django — the Python questions freshers actually face, curated from the mock interviews we run at The Kiran Academy, with notes on how interviewers dig deeper.
🐍 Python Basics 7 questions
1Why is Python so popular — what would you highlight in an interview?▾
2Is Python interpreted or compiled?▾
.pyc), which the Python Virtual Machine then interprets line by line. In interviews say "interpreted language with a bytecode compilation step" — it shows you know what actually happens, not just the label. 3List vs tuple?▾
4What are mutable and immutable types in Python?▾
5How does a dictionary work and when do you use it?▾
6== vs is?▾
== compares values (calls __eq__); is compares identity — same object in memory. Use is only for None checks (if x is None). Small integers and short strings are interned, so is may "work" accidentally and then break in production — a favourite trick question. a = [1, 2]; b = [1, 2]
print(a == b) # True - same value
print(a is b) # False - different objects
print(a is not None) # the correct use of 'is'
7What is slicing? What does [::-1] do?▾
seq[start:stop:step] extracts a part of a sequence — works on strings, lists, tuples. Defaults: start 0, stop end, step 1. s[::-1] reverses the sequence (step -1 walks backwards) — the one-line answer to "reverse a string in Python". 🧩 Functions & Scope 6 questions
8What are *args and **kwargs?▾
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. They let a function accept any number of arguments — and on the calling side, */** unpack sequences/dicts into arguments. def order(*items, **details):
print(items) # ('tea', 'samosa')
print(details) # {'table': 4, 'paid': True}
order('tea', 'samosa', table=4, paid=True)
9What is a lambda function and where would you actually use one?▾
lambda x: x * 2. Used inline where a small function is needed once — as the key for sorted()/max()/min(), or with map()/filter(). If it needs a name or more than one expression, write a normal def. 10Explain Python variable scope (LEGB).▾
global (or nonlocal for the enclosing scope) — which is why reading a global works but incrementing it without the keyword throws UnboundLocalError. 11What is the mutable default argument trap?▾
def add(item, bucket=[]) shares one list across all calls — items accumulate mysteriously. The idiom: default to None and create the list inside. def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
12What is a decorator?▾
@name above the definition. Used for cross-cutting behaviour without touching the function body: logging, timing, authentication checks, caching (@lru_cache), route registration in Flask/Django. def log_calls(func):
def wrapper(*args, **kwargs):
print(f'calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@log_calls
def pay(amount): ...
13What is a generator and how is yield different from return?▾
return ends the function with one value. yield pauses it, hands out a value, and resumes from the same point on the next request — making the function a generator that produces values lazily, one at a time, without holding everything in memory. Reading a 10GB log file line by line is the classic use; also note generator expressions: (x*x for x in nums). 🏗️ OOP in Python 6 questions
14What is self and why does Python need it?▾
self is the explicit reference to the instance a method is called on — Python passes it automatically as the first argument (obj.method() becomes Class.method(obj)). Unlike Java's implicit this, Python makes it visible: explicit is better than implicit, per the Zen of Python. 15What does __init__ do? Is it a constructor?▾
__new__ creates the object and __init__ initialises it, so "initialiser" is the precise word; in everyday speech everyone calls it the constructor, and saying both earns the point. 16Class variable vs instance variable?▾
self and unique per object. The trap: assigning through an instance (obj.count = 5) creates a NEW instance variable shadowing the class one — mutation vs assignment behave differently for mutable class variables. 17How does inheritance work in Python? What is MRO?▾
class Child(Parent); Python supports multiple inheritance. MRO (Method Resolution Order) is the deterministic order (C3 linearisation) Python searches classes for a method — inspect it with ClassName.mro(). super() follows the MRO, which is how diamond inheritance stays sane. 18What are dunder (magic) methods? Name the useful ones.▾
__str__ (print), __repr__ (debugging), __len__ (len()), __eq__/__lt__ (comparisons), __getitem__ (indexing), __enter__/__exit__ (with-statement), __call__ (make instances callable). Implementing them makes your objects feel native. 19@staticmethod vs @classmethod?▾
@staticmethod — no automatic first argument; just a function namespaced in the class (helpers). @classmethod — receives the class as cls; the standard tool for alternative constructors like Date.from_string("2026-06-13"), and it respects subclassing (cls is the actual subclass). Knowing the answer and saying it under pressure are different skills.
Our Mock Interview Program runs you through real Python interview rounds — core concepts, coding on paper, and HR — until these answers come out naturally.
📦 Data Structures & Comprehensions 5 questions
20What is a list comprehension? Rewrite a loop as one.▾
# loop
squares = []
for n in range(10):
if n % 2 == 0:
squares.append(n * n)
# comprehension
squares = [n * n for n in range(10) if n % 2 == 0]
21Shallow copy vs deep copy?▾
list(a), a[:], copy.copy) — new outer container, but inner objects are shared; mutating a nested list shows up in both. Deep copy (copy.deepcopy) — recursively copies everything; fully independent, slower. Assignment (b = a) copies nothing — just a second name for the same object. 22How do you sort complex data — list of dicts by a key?▾
sorted(data, key=lambda d: d["salary"], reverse=True) — the key function decides the sort value; sorted() returns a new list while list.sort() sorts in place. For multiple keys return a tuple from key, or use operator.itemgetter("dept", "salary"). Python's sort is stable — equal elements keep their order, which makes multi-pass sorting work. 23How would you remove duplicates from a list while keeping order?▾
list(set(items)) removes duplicates but destroys order. Order-preserving idiom: list(dict.fromkeys(items)) — dict keys are unique and insertion-ordered since 3.7. Saying both, with the trade-off, is the complete answer. 24When do you use a set?▾
if x in seen on a list is O(n)), de-duplication, and set algebra — union, intersection, difference — which turns "items in list A but not in B" into one readable expression: set(a) - set(b). ⚠️ Exceptions & Files 4 questions
25Explain try / except / else / finally.▾
try — the risky code. except — handles named exception types (catch specific exceptions, never bare except:). else — runs only if NO exception occurred (the rarely-known part interviewers probe). finally — always runs, exception or not: cleanup. Raise your own with raise ValueError("msg"). 26What does the with statement do?▾
with open(f) as fh: closes the file even if an exception occurs, replacing try/finally boilerplate. Anything implementing __enter__/__exit__ works: files, DB connections, locks. You can write your own with @contextlib.contextmanager. 27How do you read a huge file without running out of memory?▾
read() the whole file — iterate it: for line in fh: streams one line at a time (file objects are lazy iterators). For fixed-size chunks, loop on fh.read(8192). This is the practical face of generators, and the expected answer for any "10GB log file" question. 28Which built-in exceptions should a fresher recognise on sight?▾
ValueError (right type, wrong value: int("abc")), TypeError (wrong type: "a" + 1), KeyError (missing dict key) vs IndexError (list index out of range), AttributeError (often from a None you did not expect), NameError, and ZeroDivisionError. Recognising tracebacks fast is what the question really tests. 🚀 Memory, GIL & Environment 5 questions
29What is the GIL and what does it mean for multithreading?▾
multiprocessing (separate processes, separate GILs) for that. Threads remain useful for I/O-bound work (network calls, file waits) because the GIL is released during I/O. 30How does Python manage memory?▾
del removes a name, not necessarily the object. 31Module vs package? How does import actually work?▾
.py file; a package is a directory of modules (historically marked by __init__.py). On import, Python searches sys.path, executes the module ONCE, and caches it in sys.modules — re-imports are free, and module-level code runs only on first import. if __name__ == "__main__": distinguishes run-as-script from imported. 32What are virtual environments and why does every project need one?▾
python -m venv venv, activate, then pip install -r requirements.txt. Freezing dependencies with pip freeze > requirements.txt is what makes a project reproducible on another machine. 33Multithreading vs multiprocessing vs asyncio — one line each?▾
🌐 Django & Practical Python 5 questions
34Explain Django's MVT architecture.▾
35What is the Django ORM and why use it over raw SQL?▾
Student.objects.filter(city="Pune").order_by("-marks"). Benefits: no SQL injection by construction, database-agnostic code, migrations generated from model changes. Know the escape hatch (raw()) and the classic pitfall: the N+1 query problem, solved with select_related/prefetch_related. 36Django vs Flask — how do you choose?▾
37How do you build and test a REST API in Python?▾
pytest with the framework's test client asserting status codes and JSON bodies, and Postman for manual/exploratory checks. Mention JSON serialization (json.dumps/loads) and status-code correctness — 201 for created, 400 for bad input. 38Which coding problems should a Python fresher practise before interviews?▾
collections.Counter), find duplicates in a list, FizzBuzz, fibonacci with and without recursion, second-largest number without sort(), and merging two dicts. In our mock interviews these come up constantly — practise writing them on paper, talking aloud. Want Python interviews to feel like revision, not exams?
Our 6-month Python Full Stack course covers everything here in depth — plus Django, REST APIs, projects, and placement support until you are hired. Free demo class, no commitment.