The Ultimate Backend Interview Question Bank
If you're preparing for a backend or full-stack role - or just want to solidify your foundations - this is the most comprehensive question bank I've put together.
This covers everything that actually comes up in real interviews: from Git workflows and database internals to Python deep dives, system design, concurrency, and algorithms. Whether you're a fresher prepping for your first SDE role or an experienced dev brushing up before switching jobs, there's something here for every level.
I've organized it into 22 sections so you can target exactly what you need, skip what you know, deep-dive what you don't.
How to use this: Don't try to memorize answers. Use these as prompts to understand the concept. If you can explain it out loud in plain English, you know it.
What's covered
| # | Topic |
|---|---|
| 1 | Git & GitHub |
| 2 | PostgreSQL |
| 3 | MongoDB |
| 4–20 | Python (Basics, OOP, Concurrency, Memory, Testing & more) |
| 21 | System Design & Architecture |
| 22 | Data Structures & Algorithms |
Table of Contents
- Git & GitHub
- PostgreSQL
- MongoDB
- Python — Basics & Built-ins
- Python — Data Structures & Collections
- Python — Functions & Functional Programming
- Python — OOP (Object-Oriented Programming)
- Python — Modules, Packages & Imports
- Python — File Handling & I/O
- Python — Error & Exception Handling
- Python — Iterators, Generators & Comprehensions
- Python — Decorators & Context Managers
- Python — Concurrency & Parallelism
- Python — Memory Management & Internals
- Python — Standard Library & Useful Modules
- Python — Type Hints & Annotations
- Python — Testing
- Python — Database Integration
- Python — Web & APIs
- Python — Advanced Topics
- System Design / Architecture Questions
- Data Structures & Algorithms (Bonus)
1. Git & GitHub
🔹 Conceptual Questions
- What is Git? How is it different from GitHub?
- What is the difference between
git fetchandgit pull? - What is the difference between
git mergeandgit rebase? When would you use each? - What is a detached HEAD state? How do you get into it and how do you recover?
- What is the difference between
git reset,git revert, andgit restore? - What is
git stash? When would you use it? - What is
git cherry-pick? Give a use case. - What is the difference between
--soft,--mixed, and--hardingit reset? - What is a Git hook? Give examples of pre-commit and post-commit hooks.
- What is
git bisect? How does it help in debugging? - What is the difference between
originandupstreamin Git? - What is a
.gitignorefile? How do you ignore an already tracked file? - What is the difference between a
tagand abranch? - What is
git reflogand when is it useful? - What is the difference between a fast-forward merge and a three-way merge?
🔹 Branching & Workflow Questions
- Explain the Git Flow branching strategy.
- What is trunk-based development? How is it different from Git Flow?
- What is the purpose of a
develop,main,release, andhotfixbranch? - How do you handle a situation where two developers edit the same file?
- What is a pull request / merge request? What is its purpose beyond code merging?
- How do you squash commits before merging a PR?
- What is code review? What do you look for in a code review?
🔹 Scenario-Based Questions
- Scenario: You accidentally committed sensitive credentials to a public repo. What do you do?
- Scenario: You have a bug in production. Your last 5 commits are all broken. How do you roll back safely without losing other developers' work?
-
Scenario: You are working on a feature branch for 2 weeks. The
mainbranch has moved ahead by 30 commits. How do you bring your branch up to date? -
Scenario: You need to move the last 3 commits from
mainto a new feature branch because you committed to the wrong branch. - Scenario: Two team members have merge conflicts on the same PR. How do you resolve it?
-
Scenario: Your
git pullfails due to diverged branches. What are your options? - Scenario: You want to apply a bug fix from one branch to multiple other branches. What do you do?
-
Scenario: A junior developer force-pushed to the shared
mainbranch and erased commits. How do you recover?
🔹 GitHub Specific Questions
- What is GitHub Actions? How does a CI/CD pipeline work with it?
- What is the difference between a fork and a clone?
- What are GitHub branch protection rules? Why are they important?
- What is
CODEOWNERSin GitHub? - What is the difference between Issues, Milestones, and Projects in GitHub?
2. PostgreSQL
🔹 Conceptual / Fundamentals
- What is PostgreSQL? How is it different from MySQL?
- What are the ACID properties? Explain each with an example.
- What is the difference between
CHAR,VARCHAR, andTEXTin PostgreSQL? - What is the difference between
SERIAL,BIGSERIAL, andUUIDas primary key types? - What is a schema in PostgreSQL? How is it different from a database?
- What is the difference between
TRUNCATE,DELETE, andDROP? - What are sequences in PostgreSQL? How do you create and use them?
- What is the difference between
IS NULLand= NULL? - What is
COALESCE? Give a practical example. - What are CTEs (Common Table Expressions)? How are they different from subqueries?
🔹 Joins & Queries
- What is the difference between
INNER JOIN,LEFT JOIN,RIGHT JOIN, andFULL OUTER JOIN? - What is a
CROSS JOIN? When would you use it? - What is a
SELF JOIN? Give a real-world example. - What is the difference between
UNIONandUNION ALL? - What is the difference between
WHEREandHAVING? - What is the
DISTINCT ONclause in PostgreSQL? - What is a window function? Explain
ROW_NUMBER(),RANK(),DENSE_RANK(), andLAG()/LEAD(). - Write a query to find the second highest salary from an
employeestable. - Write a query to find duplicate records in a table.
- Write a query to delete duplicate rows while keeping one.
🔹 Indexing & Performance
- What is an index? What are the types of indexes in PostgreSQL?
- What is the difference between a
B-Treeindex and aHashindex? - What is a partial index? When is it useful?
- What is a composite index? What is column order importance?
- What is
EXPLAINandEXPLAIN ANALYZE? How do you read a query plan? - What is a table scan vs an index scan vs an index-only scan?
- What causes an index not to be used by the query planner?
- What is vacuuming in PostgreSQL? Why is it needed?
- What is
pg_stat_activity? What do you use it for? - What is connection pooling? Why is it important in PostgreSQL?
🔹 Transactions & Concurrency
- What are transaction isolation levels in PostgreSQL?
- What is the difference between
READ COMMITTEDandREPEATABLE READ? - What is a dirty read, non-repeatable read, and phantom read?
- What is
SELECT FOR UPDATE? When do you use it? - What is a deadlock in PostgreSQL? Give a real-world scenario.
- How does PostgreSQL handle deadlock detection?
- What is MVCC (Multi-Version Concurrency Control)?
- What is an optimistic lock vs a pessimistic lock?
- What is
SAVEPOINTin a transaction? - What is a two-phase commit?
🔹 Schema Design & Advanced
- What is normalization? Explain 1NF, 2NF, 3NF, and BCNF.
- What is denormalization? When is it preferred?
- What is a foreign key constraint? What are
ON DELETE CASCADEandON DELETE SET NULL? - What is a
CHECKconstraint? Give an example. - What is a
UNIQUEconstraint vs aPRIMARY KEY? - What is a materialized view? How is it different from a regular view?
- What are table partitioning strategies in PostgreSQL?
- What is
JSONvsJSONBin PostgreSQL? When would you use each? - What is full-text search in PostgreSQL? What are
tsvectorandtsquery? - What is the
pg_dumpandpg_restoretool? How do you take backups?
🔹 PostgreSQL vs MySQL
- What are the key differences between PostgreSQL and MySQL?
- Why would you choose PostgreSQL over MySQL for a new project?
- Which supports better ACID compliance — PostgreSQL or MySQL (InnoDB)?
- How does PostgreSQL handle JSON differently from MySQL?
- What are the replication options in PostgreSQL vs MySQL?
3. MongoDB
🔹 Conceptual / Fundamentals
- What is MongoDB? How is it different from a relational database?
- What is a document in MongoDB? What format does it use?
- What is a collection? How is it different from a table in SQL?
- What is the
_idfield in MongoDB? Can you override it? - What is BSON? How is it different from JSON?
- What are the different data types supported in MongoDB?
- What is MongoDB Atlas? How is it different from self-hosted MongoDB?
- What is the difference between
insertOne(),insertMany(), andbulkWrite()? - What is the difference between
findOne()andfind()? - What is a cursor in MongoDB?
🔹 Querying
- How do you perform conditional queries using
$gt,$lt,$gte,$lte,$ne? - What is the
$inoperator? Give an example. - What is the
$and,$or,$not, and$noroperator? - How do you query nested documents in MongoDB?
- How do you query array fields using
$elemMatch? - What is the
$regexoperator in MongoDB? - How do you perform a text search in MongoDB?
- What is the
$existsoperator? - How do you sort and limit query results in MongoDB?
- What is projection in MongoDB? How do you include/exclude fields?
🔹 Aggregation
- What is the Aggregation Pipeline in MongoDB?
- Explain the following stages:
$match,$group,$sort,$project,$limit,$skip,$unwind,$lookup. - What is
$lookup? How does it compare to SQL JOINs? - What is
$unwind? When is it useful? - Write an aggregation pipeline to find the total sales per product category.
- What is
$facetin MongoDB aggregation? - What is
$bucketand$bucketAuto? - What is
$addFieldsvs$project? - What is the difference between
$sum,$avg,$min,$maxin$group? - What is
$graphLookup? When is it used?
🔹 Indexing & Performance
- What types of indexes does MongoDB support?
- What is a compound index in MongoDB? What is field order significance?
- What is a multikey index? When is it automatically created?
- What is a text index in MongoDB?
- What is a TTL (Time-To-Live) index? Give a use case.
- What is the
explain()method? What doesexecutionStatstell you? - What is a covered query in MongoDB?
- What is the
$hintoperator in MongoDB? - What is index intersection in MongoDB?
- What is the WiredTiger storage engine?
🔹 Schema Design & Modeling
- What is embedding vs referencing in MongoDB schema design?
- When should you embed documents vs reference them?
- What is the one-to-many relationship pattern in MongoDB?
- What is the many-to-many relationship pattern in MongoDB?
- What is the Bucket Pattern in MongoDB?
- What is the Outlier Pattern?
- What is the Subset Pattern?
- What is the Extended Reference Pattern?
- What is schema validation in MongoDB?
- What is GridFS? When do you use it?
🔹 Transactions & Replication
- Does MongoDB support ACID transactions? Since which version?
- What is a replica set in MongoDB?
- What is a primary and secondary node? What happens if the primary goes down?
- What is read preference in MongoDB?
- What is write concern in MongoDB?
- What is a sharded cluster in MongoDB?
- What is a shard key? How do you choose a good one?
- What is the difference between a hashed shard key and a ranged shard key?
- What is an oplog in MongoDB?
- What is change streams in MongoDB?
4. Python — Basics & Built-ins
🔹 Language Fundamentals
- What is Python? What makes it different from compiled languages like Java or C++?
- What is PEP 8? Why does it matter?
- What is the difference between Python 2 and Python 3?
- Is Python interpreted or compiled? Explain the execution model.
- What is a
.pycfile? What is the__pycache__directory? - What are Python's key features? (dynamic typing, garbage collection, etc.)
- What is the difference between
==andis? - What is the difference between mutable and immutable objects? Give examples of each.
- What is dynamic typing in Python?
- What is duck typing?
🔹 Variables & Data Types
- What are Python's built-in data types?
- What is the difference between
int,float,complex? - What is
Nonein Python? What type is it? - What is the difference between
str,bytes, andbytearray? - How does Python handle integer overflow?
- What is the difference between
True/Falseand1/0in Python? - What is type casting? How do you convert between types?
- What is
id()in Python? What does it return? - What is integer caching (interning) in Python? (caches -5 to 256)
- What is string interning in Python?
🔹 Operators
- What are Python's arithmetic operators?
- What is the difference between
/and//in Python? - What is the
%operator? What is it used for beyond modulo? - What is the
**operator? - What are comparison operators and what do they return?
- What are Python's logical operators (
and,or,not)? How do they short-circuit? - What are bitwise operators in Python? (
&,|,^,~,<<,>>) - What is the walrus operator (
:=)? Give a use case. - What are augmented assignment operators?
- What is operator precedence in Python?
🔹 Control Flow
- What is the difference between
if,elif, andelse? - What is a ternary expression in Python?
- What is the difference between
forandwhileloops? - What is the
elseclause on afororwhileloop? When does it execute? - What is
break,continue, andpass? - What is
range()? How is it memory efficient? - What is
enumerate()? Why is it preferred over using an index? - What is
zip()? What happens if the iterables are of different lengths? - What is
reversed()? How is it different from[::-1]? - What is
sorted()vs.sort()? What is thekeyargument?
🔹 Strings
- Is a Python string mutable or immutable?
- What is string slicing? Give examples including step slicing.
- What are f-strings? How do they compare to
.format()and%formatting? - What is the difference between
split()andrsplit()? - What is
join()? Why is it preferred over string concatenation in a loop? - What are common string methods:
strip(),lstrip(),rstrip(),replace(),find(),count(),startswith(),endswith()? - What is
encode()anddecode()in Python strings? - What is a raw string (
r"...")? When do you use it? - What is string multiplication and string addition?
- How does Python handle Unicode strings?
5. Python — Data Structures & Collections
🔹 Lists
- How is a Python list stored in memory?
- What is the time complexity of common list operations: append, insert, delete, search, access by index?
- What is the difference between
append()andextend()? - What is
list.copy()vslist[:]vscopy.copy()? - What is
list.pop()vsdel list[i]vslist.remove()? - How does
sort()work internally? What algorithm does Python use? (Timsort) - What is
list.index()vslist.count()? - What is a 2D list? How do you create and access elements?
- How do you flatten a nested list in Python?
- What is the difference between
list * nand[list] * n? (shallow copy trap)
🔹 Tuples
- What is a tuple? How is it different from a list?
- Can you modify elements inside a tuple? What about mutable elements inside a tuple?
- What is tuple unpacking? Give examples.
- What is the
*operator in tuple unpacking? - What is a named tuple? How do you create one?
- Why are tuples faster than lists?
- When should you use a tuple over a list?
- What is a single-element tuple? What is the syntax pitfall?
- How do you convert a list to a tuple and vice versa?
- Can tuples be used as dictionary keys? Why?
🔹 Dictionaries
- How is a Python dictionary implemented internally? (hash table)
- What is the time complexity of dictionary operations (get, set, delete)?
- What is the difference between
dict.get()anddict[key]? - What is
dict.setdefault()? - What is
collections.defaultdict? Give a use case. - What is
collections.OrderedDict? Is it still necessary in Python 3.7+? - What is
collections.Counter? Give a use case. - What are dictionary views:
keys(),values(),items()? - How do you merge two dictionaries? (multiple ways:
|,update(),**unpacking) - What is a dictionary comprehension?
- What is
dict.update()? - What is
dict.pop()vsdel dict[key]? - What is
dict.fromkeys()? - How do you sort a dictionary by value?
- What is a nested dictionary? How do you safely access nested keys?
🔹 Sets
- What is a Python set? What are its properties?
- What is the time complexity of
infor a set vs a list? - What are set operations: union (
|), intersection (&), difference (-), symmetric difference (^)? - What is the difference between
set.discard()andset.remove()? - What is a frozenset? How is it different from a set?
- Can a set contain another set? What about a list? Why?
- What is
set.update()vs|=? - How do you find common elements between two lists efficiently?
- What is
set.issubset()andset.issuperset()? - How do you remove duplicates from a list using a set?
🔹 Collections Module
- What is
collections.deque? Why is it better than a list for queues? - What is the time complexity of
deque.appendleft()vslist.insert(0, x)? - What is
collections.ChainMap? - What is
collections.namedtuplevs a regular tuple vs a dataclass? - What is
collections.UserDict,UserList,UserStringand when do you use them?
6. Python — Functions & Functional Programming
🔹 Function Basics
- How do you define a function in Python?
- What is the difference between a parameter and an argument?
- What are default arguments? What is the mutable default argument trap?
- What is
*args? How is it different from a list parameter? - What is
**kwargs? How is it different from a dict parameter? - What is the order of parameters: positional,
*args, keyword-only,**kwargs? - What is a keyword-only argument (parameters after
*)? - What is a positional-only argument (parameters before
/)? (Python 3.8+) - What is the
returnstatement? Can a function return multiple values? - What happens if a function has no
returnstatement?
🔹 Scope & Closures
- What is the LEGB rule in Python (Local, Enclosing, Global, Built-in)?
- What is the
globalkeyword? When would you use it? - What is the
nonlocalkeyword? Give a use case. - What is a closure in Python?
- What is a free variable?
- How do closures capture variables? What is the late binding problem?
- Write a counter function using closures.
- What is the difference between a closure and a class?
- What is a first-class function in Python?
- What is a higher-order function?
🔹 Lambda & Functional Tools
- What is a lambda function? What are its limitations?
- What is
map()? Give an example. - What is
filter()? Give an example. - What is
reduce()fromfunctools? Give an example. - What is
functools.partial()? Give a use case. - What is
functools.lru_cache()? How does it work? - What is
functools.wraps()? Why is it needed in decorators? - What is
functools.total_ordering()? - What is
functools.cache()vslru_cache()? - What is
operatormodule? Give examples ofoperator.itemgetterandoperator.attrgetter.
🔹 Recursion
- What is recursion? What is a base case?
- What is the maximum recursion depth in Python? How do you change it?
- What is tail recursion? Does Python optimize tail calls?
- Write a recursive function for factorial.
- Write a recursive function for Fibonacci. What is its time complexity?
- What is memoization? How does it improve recursive functions?
- What is the difference between recursion and iteration?
- What is mutual recursion?
- What is a recursive data structure?
- When should you avoid recursion in Python?
7. Python — OOP (Object-Oriented Programming)
🔹 Classes & Objects
- What is the difference between a class and an object (instance)?
- What is
self? Why is it the first parameter of instance methods? - What is
__init__? How is it different from__new__? - What are class variables vs instance variables? What happens when they share a name?
- What is
__dict__on a class and on an instance? - What is
vars()in Python? - What is
dir()in Python? - What is
hasattr(),getattr(),setattr(),delattr()? - How do you check if an object is an instance of a class? (
isinstance()) - How do you check if a class is a subclass of another? (
issubclass())
🔹 The Four Pillars
- What is Encapsulation? How do you implement it in Python?
- What is the difference between
_name(convention),__name(name mangling), and__name__(dunder)? - What is Abstraction? How does it differ from encapsulation?
- What is Inheritance? Give an example.
- What is single vs multiple inheritance in Python?
- What is the MRO (Method Resolution Order)? What is the C3 linearization algorithm?
- How do you find the MRO of a class? (
ClassName.__mro__ormro()) - What is Polymorphism? Give a Python example.
- What is method overriding? How does it work in Python?
- Does Python support method overloading? How do you simulate it?
🔹 Special / Dunder Methods
- What is
__str__vs__repr__? Which is called in which situation? - What is
__len__? - What is
__getitem__,__setitem__,__delitem__? - What is
__iter__and__next__? - What is
__contains__(enablesinoperator)? - What is
__call__? How do you make an object callable? - What is
__eq__,__lt__,__gt__,__le__,__ge__,__ne__? - What is
__add__,__sub__,__mul__,__truediv__? (operator overloading) - What is
__enter__and__exit__? (context manager protocol) - What is
__slots__? What are its advantages and limitations? - What is
__init_subclass__? Give a use case. - What is
__del__? When is it called? Is it reliable? - What is
__hash__? What is the relationship between__eq__and__hash__? - What is
__bool__? When is it called vs__len__? - What is
__missing__in a dict subclass?
🔹 Class Methods & Properties
- What is
@staticmethod? When would you use it? - What is
@classmethod? When would you use it? - What is the difference between
@staticmethodand@classmethod? - What is
@property? What is a getter and setter in Python? - What is a
@property.setterand@property.deleter? - When would you use a property vs a regular method?
- What is a class factory method? Give an example.
- What is
__new__used for? Give a practical example (e.g., Singleton). - What is
type()used as a metaclass? How do you create a class dynamically? - What is
object.__class__?
🔹 Inheritance & Advanced OOP
- What is
super()? How does it work with multiple inheritance? - What is a mixin? Give a real-world use case.
- What is composition vs inheritance? When do you prefer composition?
- What is an abstract class? How do you create one using the
abcmodule? - What is
@abstractmethod? What happens if you don't implement it? - What is the difference between an abstract class and an interface (Protocol)?
- What is
typing.Protocol? How is it used for structural subtyping? - What is a dataclass (
@dataclass)? What does it auto-generate? - What are the parameters of
@dataclass:frozen,order,eq,repr? - What is
field()in dataclasses? What isdefault_factory? - What is
__post_init__in dataclasses? - What is
NamedTuplevsdataclassvs regular class? - What is the
Enumclass? How do you define an enumeration? - What is
IntEnum,StrEnum,Flag,IntFlag? - What is a descriptor in Python? What are
__get__,__set__,__delete__?
🔹 Design Patterns
- Implement the Singleton pattern in Python (at least 2 ways).
- Implement the Factory pattern in Python.
- Implement the Abstract Factory pattern.
- Implement the Observer pattern in Python.
- Implement the Strategy pattern in Python.
- Implement the Decorator design pattern (not Python
@decorator) in Python. - Implement the Command pattern in Python.
- Implement the Iterator pattern using
__iter__and__next__. - What is dependency injection? Give a Python example.
- What is the Repository pattern and why is it used with databases?
8. Python — Modules, Packages & Imports
🔹 Modules & Packages
- What is a module in Python?
- What is a package? What is
__init__.py? What is a namespace package? - What is the difference between
import moduleandfrom module import name? - What is
import *? Why is it discouraged? - What is
__all__in a module? - What is a relative import vs absolute import?
- What is
importlib? How do you import a module dynamically? - What is
sys.path? How does Python find modules? - What is
__name__ == "__main__"? Why is it used? - What is the difference between a script and a module?
- What is
__file__in a module? - How do you reload a module at runtime?
- What is a circular import? How do you resolve it?
- What is a virtual environment? Why is it important?
- What is
__package__attribute?
🔹 Package Management
- What is
pip? How do you install, uninstall, upgrade, and list packages? - What is
requirements.txt? How do you generate it? - What is the difference between
pip installandpip install -e(editable mode)? - What is
pyproject.toml? How is it different fromsetup.py? - What is
venvvsvirtualenvvsconda?
9. Python — File Handling & I/O
🔹 File Operations
- How do you open a file in Python? What are the different modes (
r,w,a,rb,wb,r+)? - What is the
withstatement for file handling? Why is it preferred? - What is the difference between
read(),readline(), andreadlines()? - What is the difference between
write()andwritelines()? - What is
seek()andtell()? - How do you check if a file exists?
- How do you copy, move, rename, and delete files in Python?
- What is
os.pathvspathlib.Path? Which is preferred and why? - How do you list files in a directory? How do you walk a directory tree?
- What is
glob? Give a use case. - How do you read a large file line by line without loading it into memory?
- What is
tempfilemodule? When do you use it? - What is
shutil? What can it do? - How do you work with CSV files in Python? (
csvmodule) - How do you work with JSON files in Python?
🔹 Serialization
- What is
pickle? What are the security risks of using it? - What is
json.dumps()vsjson.dump()? What is the difference? - What is
json.loads()vsjson.load()? - What is the
indentandseparatorsargument injson.dumps()? - What is
shelve? When would you use it?
10. Python — Error & Exception Handling
🔹 Exception Basics
- What is an exception in Python? How is it different from a syntax error?
- What is the difference between
ExceptionandBaseException? - What are built-in exceptions? Name at least 15. (
ValueError,TypeError,KeyError,IndexError,AttributeError,NameError,ImportError,OSError,RuntimeError,StopIteration,NotImplementedError,ZeroDivisionError,OverflowError,MemoryError,RecursionError) - What is the exception hierarchy in Python?
- What is
try,except,else,finally? - What is the
elseclause in a try block? When does it run? - What is the
finallyclause? Does it always execute? - Can you have multiple
exceptblocks? Can you catch multiple exceptions in one block? - What is the order of
exceptblocks? Does it matter? (more specific first) - What is a bare
except:? Why is it dangerous?
🔹 Raising & Custom Exceptions
- What is
raise? How do you re-raise the current exception? - What is
raise ... from ...? What does it do to the traceback? - How do you create a custom exception class?
- What is exception chaining? What is
__cause__and__context__? - What is
warningsmodule? How is it different from exceptions? - What is
contextlib.suppress()? - What is
ExceptionGroupin Python 3.11+? - What is
except*syntax in Python 3.11+? - What is
sys.exc_info()? - Best practices: When should you catch exceptions broadly vs specifically?
11. Python — Iterators, Generators & Comprehensions
🔹 Iterators & Iterables
- What is an iterable? What is an iterator?
- What is the iterator protocol? (
__iter__and__next__) - What is
StopIteration? How is it raised? - What is the difference between calling
iter()andnext()built-ins? - What is lazy evaluation? How do iterators implement it?
- What is
itertoolsmodule? Name at least 10 functions from it. - What is
itertools.chain()? - What is
itertools.islice()? - What is
itertools.product()? - What is
itertools.groupby()? What is its sorting requirement gotcha? - What is
itertools.cycle()? - What is
itertools.accumulate()? - What is
itertools.combinations()vsitertools.permutations()? - What is
itertools.zip_longest()? - What is
itertools.starmap()?
🔹 Generators
- What is a generator function? What makes it a generator?
- What is
yield? How is it different fromreturn? - What is
yield from? Give a use case. - What is a generator expression? How does it differ from a list comprehension?
- How does
send()work on a generator? - How does
throw()work on a generator? - How does
close()work on a generator? What exception is raised internally? (GeneratorExit) - What are the states of a generator? (created, running, suspended, closed)
- What are the memory advantages of generators over lists?
- Write an infinite generator for Fibonacci numbers.
- What is
next()with a default value? - Write a generator pipeline for processing large files.
- What is
inspect.isgenerator()vsinspect.isgeneratorfunction()? - What is
types.GeneratorType? - How do you convert a generator to a list? What are the implications?
🔹 Comprehensions
- What is a list comprehension? What is its syntax?
- What is a dictionary comprehension?
- What is a set comprehension?
- What is a generator expression vs a list comprehension?
- Can you have nested comprehensions? Give an example.
- What are the performance implications of list comprehensions vs for loops?
- What is a conditional comprehension (with
ifclause as filter)? - What is the difference between
[x for x in range(10) if x > 5]and[x if x > 5 else 0 for x in range(10)]? - When should you NOT use a comprehension?
- What is variable leaking in Python 2 list comprehensions vs Python 3?
12. Python — Decorators & Context Managers
🔹 Decorators
- What is a decorator in Python?
- How do you write a simple function decorator?
- What is
functools.wraps()? Why must you use it in decorators? - What is a decorator with arguments? How do you write one (decorator factory)?
- What is a class-based decorator? How does
__call__enable it? - What is the order of stacked decorators? Which applies first?
- Write a decorator that measures function execution time.
- Write a decorator that retries a function on exception (with max retries).
- Write a decorator that caches function results (manual
lru_cache). - Write a decorator that validates function argument types.
- What is
@staticmethod,@classmethod,@property— are these decorators? - What is
@functools.lru_cache? What aremaxsizeandtypedparameters? - What is
@functools.cached_property? How is it different from@property? - What is a parametrized decorator factory?
- What are real-world use cases for decorators? (logging, auth, rate limiting, caching, timing)
🔹 Context Managers
- What is a context manager? What protocol does it use?
- What is
__enter__and__exit__? - What do the arguments of
__exit__(exc_type, exc_val, exc_tb)mean? - How do you suppress an exception inside
__exit__? - What is
contextlib.contextmanager? How do you write a generator-based context manager? - What is
contextlib.suppress()? - What is
contextlib.ExitStack()? When is it useful? - What is
contextlib.asynccontextmanager? - Write a context manager for timing code execution.
- Write a context manager that manages a database connection.
13. Python — Concurrency & Parallelism
🔹 Core Concepts
- What is the difference between concurrency and parallelism?
- What is a process vs a thread?
- What is the GIL (Global Interpreter Lock) in Python? Why does it exist?
- How does the GIL affect CPU-bound vs I/O-bound programs?
- When does the GIL not matter?
- What is
threadingmodule vsmultiprocessingmodule? When do you use each? - What is
asyncio? How is it different from threading? - What is an event loop in asyncio?
- What is
asyncandawait? How do they work? - What is a coroutine in Python?
🔹 Threading
- How do you create and start a thread in Python?
- What is
threading.Thread? What are thetarget,args,kwargs,daemonparameters? - What is a daemon thread? What happens when the main thread exits?
- What is thread safety? How do you make code thread-safe?
- What is a
Lockin threading? - What is
RLock(Reentrant Lock)? When do you need it over a regular Lock? - What is a
Semaphore? What isBoundedSemaphore? - What is
threading.Event? Give a use case. - What is
threading.Condition? Give a producer-consumer example. - What is
threading.Barrier? - What is
threading.Timer? - What is
threading.local()? When would you use thread-local storage? - What is a race condition? Give a Python threading example.
- What is a deadlock? Give a Python threading deadlock example.
- What is thread starvation?
- What is the producer-consumer problem? How do you solve it in Python?
- What is
queue.Queue? How is it thread-safe? - What is
queue.LifoQueuevsqueue.PriorityQueue? - How do you join threads? What does
thread.join()do? - What is
threading.active_count()andthreading.enumerate()?
🔹 Multiprocessing
- What is
multiprocessing.Process? How is it different fromthreading.Thread? - How do processes share memory? What about threads?
- What is
multiprocessing.Pool? What methods does it offer? - What is the difference between
Pool.map(),Pool.starmap(),Pool.apply(),Pool.apply_async()? - What is
multiprocessing.Queue? How is it different fromqueue.Queue? - What is
multiprocessing.Pipe? What is the difference betweensend()andrecv()? - What is
multiprocessing.Valueandmultiprocessing.Array? (shared memory) - What is
multiprocessing.Manager? What objects does it support? - What is
multiprocessing.Lock()vsthreading.Lock()? - What is the difference between
fork,spawn, andforkserverstart methods? - Why is
if __name__ == '__main__'required in multiprocessing? - What is
concurrent.futures.ProcessPoolExecutor? - What is
concurrent.futures.ThreadPoolExecutor? - What is
executor.submit()vsexecutor.map()? - What is a
Futureobject inconcurrent.futures? - What is
as_completed()inconcurrent.futures? - What is
wait()inconcurrent.futures? - What is
chunksizeinPool.map()? Why does it matter for performance? - How do you handle exceptions in child processes?
- What is
multiprocessing.cpu_count()?
🔹 Asyncio & Async Programming
- What is
asyncio.run()? - What is
asyncio.create_task()? How is it different fromawait coroutine? - What is
asyncio.gather()? How does it handle exceptions? - What is
asyncio.wait()vsasyncio.gather()? - What is
asyncio.sleep()? Why nottime.sleep()in async code? - What is
asyncio.Queue? - What is
asyncio.Lock(),asyncio.Semaphore(),asyncio.Event()? - What is
asyncio.shield()? When is it useful? - How do you run a blocking (synchronous) function inside an async program?
- What is
loop.run_in_executor()? - What is
asyncio.timeout()/asyncio.wait_for()? - What is
aiohttp? How does it differ fromrequests? - What is the difference between a coroutine object and a task?
- How do you cancel an asyncio task?
- What is
asyncio.current_task()andasyncio.all_tasks()? - What are task groups (
asyncio.TaskGroup) in Python 3.11+? - What is structured concurrency?
🔹 Scenario / Real-World Questions
- Scenario: You are building a web scraper that needs to scrape 10,000 URLs. Would you use threading, multiprocessing, or asyncio? Why?
- Scenario: You have a CPU-intensive image processing task across 1 million images. Which approach do you choose?
- Scenario: You need to make 1000 HTTP API requests as fast as possible. Which approach gives the best performance?
- Scenario: Describe a real-world deadlock scenario in a web application and how you would prevent it.
- Scenario: Two threads are incrementing a shared counter. The result is always less than expected. Why? How do you fix it?
- Scenario: You have a mixed workload — some tasks are CPU-bound and some are I/O-bound. How do you architect this?
14. Python — Memory Management & Internals
🔹 Memory Management
- How does Python manage memory?
- What is reference counting in Python?
- What is the garbage collector in Python? When does it run?
- What is a reference cycle? Give an example.
- What is
gcmodule? What doesgc.collect()do? - What is
sys.getrefcount()? Why does it always return at least 1? - What is
__del__? Is it reliable? Why or why not? - What is
weakref? When would you use a weak reference? - What is a memory leak in Python? How can it happen?
- What is
tracemalloc? How do you use it to track memory usage? - What is
sys.getsizeof()? What are its limitations? - What is the small object allocator (pymalloc) in CPython?
- How do
__slots__reduce memory usage? - What is the difference between stack memory and heap memory in Python?
- What is memory fragmentation in Python?
🔹 Python Internals
- What is Python bytecode? How do you view it?
- What is the
dismodule? - What is the CPython interpreter?
- What are the alternatives to CPython? (PyPy, Jython, IronPython, MicroPython)
- What is PyPy? How is it faster than CPython? (JIT compilation)
- What is
ctypes? How can you call C functions from Python? - How does Python's
intobject handle arbitrarily large integers? - What is integer caching in CPython? Which integers are cached?
- What is string interning? Which strings are automatically interned?
- What is
__pycache__? What is the.pycfile format?
15. Python — Standard Library & Useful Modules
🔹 Must-Know Modules
- What is
osmodule? Name 10 commonly used functions/attributes. - What is
sysmodule? Name 5 commonly used attributes. - What is
pathlib? How is it different fromos.path? - What is
datetimemodule? How do you get the current date and time? - What is the difference between
datetime.date,datetime.time, anddatetime.datetime? - What is
timedelta? Give a use case. - What is
time.time()vstime.perf_counter()vstime.process_time()? - What is
randommodule? Name 5 commonly used functions. - What is
mathmodule? Name 5 commonly used functions. - What is
statisticsmodule? What functions does it provide? - What is the
remodule? What arere.match(),re.search(),re.findall(),re.sub(),re.split()? - What is the difference between
re.match()andre.search()? - What are groups in regex? What is
re.group()and named groups? - What is a compiled regex pattern? Why use
re.compile()? - What is
hashlib? Name common hash algorithms and give a use case. - What is
uuidmodule? What is the difference between UUID1, UUID4, UUID5? - What is
base64encoding? How do you encode/decode? - What is
iomodule? What isStringIOandBytesIO? - What is
loggingmodule? How do you set up basic and advanced logging? - What are logging levels? (
DEBUG,INFO,WARNING,ERROR,CRITICAL) - What is a logging handler? What is a logging formatter? What is a logging filter?
- What is
argparse? How do you parse command-line arguments? - What is
configparser? How do you read.inifiles? - What is
subprocess? How do you run a shell command from Python? - What is
subprocess.run()vssubprocess.Popen()? - What is
socketmodule? What is TCP vs UDP? - What is
copymodule? What iscopy.copy()vscopy.deepcopy()? - What is
pprint? When do you use it? - What is
decimalmodule? Why use it overfloat? (floating point precision) - What is
fractionsmodule? - What is
heapqmodule? Name its key functions. - What is
bisectmodule? What arebisect_left()andbisect_right()? - What is
arraymodule? How is it different from a list? - What is
structmodule? When is it used? - What is
textwrapmodule? - What is
difflibmodule? - What is
calendarmodule? - What is
zlibandgzipmodule? - What is
tarfileandzipfilemodule? - What is
sqlite3module?
16. Python — Type Hints & Annotations
🔹 Type Hints Basics
- What are type hints in Python? Are they enforced at runtime?
- What is the
typingmodule? - What is
Optional[T]? How is it different fromUnion[T, None]? - What is
Union[T1, T2]? What isT1 | T2syntax (Python 3.10+)? - What is
List[T],Dict[K, V],Tuple[T, ...],Set[T]? - What is
Anytype? When would you use it? - What is
Callable[[args], return_type]? - What is
TypeVar? How is it used for generic functions? - What is
Generic[T]? How do you write a generic class? - What is
Protocol? How is it used for structural typing (duck typing with types)? - What is
TypedDict? - What is
Final? How does it signal a constant? - What is
Literal? Give a use case. - What is
ClassVar? - What is
overloaddecorator intyping? - What is
mypy? How do you use it? - What is
pyright? How is it different frommypy? - What is
TYPE_CHECKING? Why is it used? - What are forward references (string annotations) in type hints?
- What is
get_type_hints()?
17. Python — Testing
🔹 Testing Fundamentals
- What is unit testing vs integration testing vs end-to-end testing?
- What is
unittestmodule? How do you write a test case? - What is
setUp()andtearDown()in unittest? - What is
setUpClass()andtearDownClass()? - What is
pytest? How is it different fromunittest? - What are pytest fixtures? How are they different from setUp/tearDown?
- What is fixture scope in pytest? (
function,class,module,session) - What is
pytest.mark.parametrize? - What is
pytest.raises? How do you test for exceptions? - What is
pytest.warns? - What is mocking in Python testing?
- What is
unittest.mock.Mock? - What is
unittest.mock.MagicMock? - What is
@patchdecorator? What does it replace? - What is
patch.object()? - What is
side_effectin Mock? How is it different fromreturn_value? - What is
assert_called_once_with()? - What is code coverage? How do you measure it with
pytest-cov? - What is TDD (Test-Driven Development)?
- What is property-based testing? What is
hypothesislibrary?
18. Python — Database Integration
🔹 Working with Databases
- What is
psycopg2? How do you connect to PostgreSQL from Python? - What is a connection vs a cursor in database programming?
- What is
cursor.execute()vscursor.executemany()? - What is a parameterized query? Why is it important for SQL injection prevention?
- What is
connection.commit()vsconnection.rollback()? - What is
pymongo? How do you connect to MongoDB from Python? - What is SQLAlchemy? What are its two main components?
- What is SQLAlchemy Core vs SQLAlchemy ORM?
- What is a SQLAlchemy
Session? - What is
declarative_base()in SQLAlchemy? - What are SQLAlchemy relationships? (
relationship(),ForeignKey) - What is lazy loading vs eager loading in SQLAlchemy?
- What is Alembic? How do you create and apply migrations?
- What is an ORM? What are its advantages and disadvantages?
- What is connection pooling in SQLAlchemy?
19. Python — Web & APIs
🔹 Web Frameworks & HTTP
- What is
requestslibrary? How do you make a GET and POST request? - What is
requests.Session()? What are its advantages? - What are request headers, query params, and request body?
- What is
requests.Response? What arestatus_code,text,json(),content? - What is
httpx? How is it different fromrequests? - What is
aiohttp? Why is it used with asyncio? - What is REST? What are the HTTP methods and their semantic meanings?
- What is Flask? Write a simple Hello World API in Flask.
- What is FastAPI? What makes it fast? (Starlette + Pydantic + async)
- What is Django? How is it different from Flask and FastAPI?
- What is middleware in web frameworks?
- What is WSGI vs ASGI?
- What is
Pydantic? How is it used for data validation in FastAPI? - What is dependency injection in FastAPI?
- What is
uvicorn? What role does it play?
20. Python — Advanced Topics
🔹 Metaclasses
- What is a metaclass in Python?
- What is
type? How is it the metaclass of all classes? - How do you create a custom metaclass?
- What are
__prepare__,__new__,__init__hooks in a metaclass? - What is
__init_subclass__? How is it used as a simpler alternative to metaclasses? - What is
abc.ABCMeta? - What is the difference between a class decorator and a metaclass?
- What are real-world use cases for metaclasses? (ORMs, plugin systems, validation)
- What is
type.__new__()vsobject.__new__()? - What is
__class_getitem__used for?
🔹 Descriptors
- What is a descriptor in Python?
- What is the difference between a data descriptor and a non-data descriptor?
- What is
__get__,__set__,__delete__in a descriptor? - How does
@propertyuse the descriptor protocol? - How do
classmethodandstaticmethoduse descriptors internally?
🔹 Advanced Python Features
- What is
__getattr__vs__getattribute__? What is the difference? - What is
__set_name__? Give a use case. - What is structural pattern matching (
match/case) in Python 3.10+? - What is
TypeAliasin Python 3.10+? - What is
ParamSpecintyping? Give a use case. - What is
Selftype in Python 3.11+? - What is
LiteralStringin Python 3.11+? - What is
zoneinfomodule? - What is
graphlibin Python 3.9+? - What is the
astmodule? How do you parse Python source code? - What is
inspectmodule? Name 5 use cases. - What is
dismodule? How do you disassemble Python bytecode? - What is
cProfile? How do you profile a Python script? - What is
line_profiler? How is it more granular thancProfile? - What is
Cython? How does it speed up Python?
21. System Design / Architecture Questions
(Based on real interview experience — these come up often)
Database Choice: You are a software architect. You have a development team and a client-facing team. How do you decide between SQL and NoSQL for the project?
-
SQL vs NoSQL trade-offs:
- When is NoSQL preferred over SQL?
- When is SQL preferred over NoSQL?
- What factors influence the decision? (data structure, scale, consistency requirements, query patterns)
PostgreSQL vs MySQL: Both are relational — why would you pick PostgreSQL over MySQL? What about the reverse?
CAP Theorem: What is the CAP theorem? Where do PostgreSQL and MongoDB fit?
ACID vs BASE: What is the difference? Which databases follow which model?
-
Real-World Deadlock: Describe a real-world deadlock scenario in a web application. How do you detect and prevent it?
Example: Two users trying to transfer money to each other simultaneously.
Scaling: How do you scale a PostgreSQL database? What about a MongoDB cluster?
Caching: When would you add a cache (like Redis) in front of a database?
Sharding vs Replication: What is the difference? When do you use each?
Schema-less vs Schema: What are the advantages and disadvantages of MongoDB's schema-less nature in a production system?
22. Data Structures & Algorithms (Bonus)
(Appeared in interviews — practice these)
- Peak Mountain Element: Given an array, find the peak element (element greater than its neighbors). What is the O(log n) approach using binary search?
- What is the difference between a stack and a queue? Implement both using Python lists.
- What is a linked list? Implement
reverse()on a singly linked list. - What is the difference between BFS and DFS? When do you use each?
- What is a binary search tree? What are its time complexities for insert, search, and delete?
- What is a hash table? How does Python's dictionary implement it internally?
- What is the two-pointer technique? Give an example problem.
- What is dynamic programming? Explain with the Fibonacci and knapsack example.
- Write a function to check if a string is a palindrome.
- What is the sliding window technique? Give an example.
- What is a heap? What is
heapqin Python? - What is the time complexity of sorting algorithms: Bubble, Selection, Insertion, Merge, Quick, Heap, Tim?
- Scenario: Given a list of integers, find all pairs that sum to a target value. What is the optimal approach?
- What is a trie? When would you use one?
- What is a graph? Explain adjacency list vs adjacency matrix representation.
- What is Dijkstra's algorithm? What data structure does it use?
- What is a topological sort? When is it used?
- What is a union-find (disjoint set) data structure?
- What is the difference between a min-heap and a max-heap?
- What is an LRU cache? Implement it in Python using
OrderedDict.
Top comments (0)