DEV Community

Cover image for Interview Questions💥: Git/GitHub · PostgreSQL · MongoDB · Python
Kishan vyas
Kishan vyas

Posted on

Interview Questions💥: Git/GitHub · PostgreSQL · MongoDB · Python

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

  1. Git & GitHub
  2. PostgreSQL
  3. MongoDB
  4. Python — Basics & Built-ins
  5. Python — Data Structures & Collections
  6. Python — Functions & Functional Programming
  7. Python — OOP (Object-Oriented Programming)
  8. Python — Modules, Packages & Imports
  9. Python — File Handling & I/O
  10. Python — Error & Exception Handling
  11. Python — Iterators, Generators & Comprehensions
  12. Python — Decorators & Context Managers
  13. Python — Concurrency & Parallelism
  14. Python — Memory Management & Internals
  15. Python — Standard Library & Useful Modules
  16. Python — Type Hints & Annotations
  17. Python — Testing
  18. Python — Database Integration
  19. Python — Web & APIs
  20. Python — Advanced Topics
  21. System Design / Architecture Questions
  22. Data Structures & Algorithms (Bonus)

1. Git & GitHub

🔹 Conceptual Questions

  1. What is Git? How is it different from GitHub?
  2. What is the difference between git fetch and git pull?
  3. What is the difference between git merge and git rebase? When would you use each?
  4. What is a detached HEAD state? How do you get into it and how do you recover?
  5. What is the difference between git reset, git revert, and git restore?
  6. What is git stash? When would you use it?
  7. What is git cherry-pick? Give a use case.
  8. What is the difference between --soft, --mixed, and --hard in git reset?
  9. What is a Git hook? Give examples of pre-commit and post-commit hooks.
  10. What is git bisect? How does it help in debugging?
  11. What is the difference between origin and upstream in Git?
  12. What is a .gitignore file? How do you ignore an already tracked file?
  13. What is the difference between a tag and a branch?
  14. What is git reflog and when is it useful?
  15. What is the difference between a fast-forward merge and a three-way merge?

🔹 Branching & Workflow Questions

  1. Explain the Git Flow branching strategy.
  2. What is trunk-based development? How is it different from Git Flow?
  3. What is the purpose of a develop, main, release, and hotfix branch?
  4. How do you handle a situation where two developers edit the same file?
  5. What is a pull request / merge request? What is its purpose beyond code merging?
  6. How do you squash commits before merging a PR?
  7. What is code review? What do you look for in a code review?

🔹 Scenario-Based Questions

  1. Scenario: You accidentally committed sensitive credentials to a public repo. What do you do?
  2. 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?
  3. Scenario: You are working on a feature branch for 2 weeks. The main branch has moved ahead by 30 commits. How do you bring your branch up to date?
  4. Scenario: You need to move the last 3 commits from main to a new feature branch because you committed to the wrong branch.
  5. Scenario: Two team members have merge conflicts on the same PR. How do you resolve it?
  6. Scenario: Your git pull fails due to diverged branches. What are your options?
  7. Scenario: You want to apply a bug fix from one branch to multiple other branches. What do you do?
  8. Scenario: A junior developer force-pushed to the shared main branch and erased commits. How do you recover?

🔹 GitHub Specific Questions

  1. What is GitHub Actions? How does a CI/CD pipeline work with it?
  2. What is the difference between a fork and a clone?
  3. What are GitHub branch protection rules? Why are they important?
  4. What is CODEOWNERS in GitHub?
  5. What is the difference between Issues, Milestones, and Projects in GitHub?

2. PostgreSQL

🔹 Conceptual / Fundamentals

  1. What is PostgreSQL? How is it different from MySQL?
  2. What are the ACID properties? Explain each with an example.
  3. What is the difference between CHAR, VARCHAR, and TEXT in PostgreSQL?
  4. What is the difference between SERIAL, BIGSERIAL, and UUID as primary key types?
  5. What is a schema in PostgreSQL? How is it different from a database?
  6. What is the difference between TRUNCATE, DELETE, and DROP?
  7. What are sequences in PostgreSQL? How do you create and use them?
  8. What is the difference between IS NULL and = NULL?
  9. What is COALESCE? Give a practical example.
  10. What are CTEs (Common Table Expressions)? How are they different from subqueries?

🔹 Joins & Queries

  1. What is the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN?
  2. What is a CROSS JOIN? When would you use it?
  3. What is a SELF JOIN? Give a real-world example.
  4. What is the difference between UNION and UNION ALL?
  5. What is the difference between WHERE and HAVING?
  6. What is the DISTINCT ON clause in PostgreSQL?
  7. What is a window function? Explain ROW_NUMBER(), RANK(), DENSE_RANK(), and LAG()/LEAD().
  8. Write a query to find the second highest salary from an employees table.
  9. Write a query to find duplicate records in a table.
  10. Write a query to delete duplicate rows while keeping one.

🔹 Indexing & Performance

  1. What is an index? What are the types of indexes in PostgreSQL?
  2. What is the difference between a B-Tree index and a Hash index?
  3. What is a partial index? When is it useful?
  4. What is a composite index? What is column order importance?
  5. What is EXPLAIN and EXPLAIN ANALYZE? How do you read a query plan?
  6. What is a table scan vs an index scan vs an index-only scan?
  7. What causes an index not to be used by the query planner?
  8. What is vacuuming in PostgreSQL? Why is it needed?
  9. What is pg_stat_activity? What do you use it for?
  10. What is connection pooling? Why is it important in PostgreSQL?

🔹 Transactions & Concurrency

  1. What are transaction isolation levels in PostgreSQL?
  2. What is the difference between READ COMMITTED and REPEATABLE READ?
  3. What is a dirty read, non-repeatable read, and phantom read?
  4. What is SELECT FOR UPDATE? When do you use it?
  5. What is a deadlock in PostgreSQL? Give a real-world scenario.
  6. How does PostgreSQL handle deadlock detection?
  7. What is MVCC (Multi-Version Concurrency Control)?
  8. What is an optimistic lock vs a pessimistic lock?
  9. What is SAVEPOINT in a transaction?
  10. What is a two-phase commit?

🔹 Schema Design & Advanced

  1. What is normalization? Explain 1NF, 2NF, 3NF, and BCNF.
  2. What is denormalization? When is it preferred?
  3. What is a foreign key constraint? What are ON DELETE CASCADE and ON DELETE SET NULL?
  4. What is a CHECK constraint? Give an example.
  5. What is a UNIQUE constraint vs a PRIMARY KEY?
  6. What is a materialized view? How is it different from a regular view?
  7. What are table partitioning strategies in PostgreSQL?
  8. What is JSON vs JSONB in PostgreSQL? When would you use each?
  9. What is full-text search in PostgreSQL? What are tsvector and tsquery?
  10. What is the pg_dump and pg_restore tool? How do you take backups?

🔹 PostgreSQL vs MySQL

  1. What are the key differences between PostgreSQL and MySQL?
  2. Why would you choose PostgreSQL over MySQL for a new project?
  3. Which supports better ACID compliance — PostgreSQL or MySQL (InnoDB)?
  4. How does PostgreSQL handle JSON differently from MySQL?
  5. What are the replication options in PostgreSQL vs MySQL?

3. MongoDB

🔹 Conceptual / Fundamentals

  1. What is MongoDB? How is it different from a relational database?
  2. What is a document in MongoDB? What format does it use?
  3. What is a collection? How is it different from a table in SQL?
  4. What is the _id field in MongoDB? Can you override it?
  5. What is BSON? How is it different from JSON?
  6. What are the different data types supported in MongoDB?
  7. What is MongoDB Atlas? How is it different from self-hosted MongoDB?
  8. What is the difference between insertOne(), insertMany(), and bulkWrite()?
  9. What is the difference between findOne() and find()?
  10. What is a cursor in MongoDB?

🔹 Querying

  1. How do you perform conditional queries using $gt, $lt, $gte, $lte, $ne?
  2. What is the $in operator? Give an example.
  3. What is the $and, $or, $not, and $nor operator?
  4. How do you query nested documents in MongoDB?
  5. How do you query array fields using $elemMatch?
  6. What is the $regex operator in MongoDB?
  7. How do you perform a text search in MongoDB?
  8. What is the $exists operator?
  9. How do you sort and limit query results in MongoDB?
  10. What is projection in MongoDB? How do you include/exclude fields?

🔹 Aggregation

  1. What is the Aggregation Pipeline in MongoDB?
  2. Explain the following stages: $match, $group, $sort, $project, $limit, $skip, $unwind, $lookup.
  3. What is $lookup? How does it compare to SQL JOINs?
  4. What is $unwind? When is it useful?
  5. Write an aggregation pipeline to find the total sales per product category.
  6. What is $facet in MongoDB aggregation?
  7. What is $bucket and $bucketAuto?
  8. What is $addFields vs $project?
  9. What is the difference between $sum, $avg, $min, $max in $group?
  10. What is $graphLookup? When is it used?

🔹 Indexing & Performance

  1. What types of indexes does MongoDB support?
  2. What is a compound index in MongoDB? What is field order significance?
  3. What is a multikey index? When is it automatically created?
  4. What is a text index in MongoDB?
  5. What is a TTL (Time-To-Live) index? Give a use case.
  6. What is the explain() method? What does executionStats tell you?
  7. What is a covered query in MongoDB?
  8. What is the $hint operator in MongoDB?
  9. What is index intersection in MongoDB?
  10. What is the WiredTiger storage engine?

🔹 Schema Design & Modeling

  1. What is embedding vs referencing in MongoDB schema design?
  2. When should you embed documents vs reference them?
  3. What is the one-to-many relationship pattern in MongoDB?
  4. What is the many-to-many relationship pattern in MongoDB?
  5. What is the Bucket Pattern in MongoDB?
  6. What is the Outlier Pattern?
  7. What is the Subset Pattern?
  8. What is the Extended Reference Pattern?
  9. What is schema validation in MongoDB?
  10. What is GridFS? When do you use it?

🔹 Transactions & Replication

  1. Does MongoDB support ACID transactions? Since which version?
  2. What is a replica set in MongoDB?
  3. What is a primary and secondary node? What happens if the primary goes down?
  4. What is read preference in MongoDB?
  5. What is write concern in MongoDB?
  6. What is a sharded cluster in MongoDB?
  7. What is a shard key? How do you choose a good one?
  8. What is the difference between a hashed shard key and a ranged shard key?
  9. What is an oplog in MongoDB?
  10. What is change streams in MongoDB?

4. Python — Basics & Built-ins

🔹 Language Fundamentals

  1. What is Python? What makes it different from compiled languages like Java or C++?
  2. What is PEP 8? Why does it matter?
  3. What is the difference between Python 2 and Python 3?
  4. Is Python interpreted or compiled? Explain the execution model.
  5. What is a .pyc file? What is the __pycache__ directory?
  6. What are Python's key features? (dynamic typing, garbage collection, etc.)
  7. What is the difference between == and is?
  8. What is the difference between mutable and immutable objects? Give examples of each.
  9. What is dynamic typing in Python?
  10. What is duck typing?

🔹 Variables & Data Types

  1. What are Python's built-in data types?
  2. What is the difference between int, float, complex?
  3. What is None in Python? What type is it?
  4. What is the difference between str, bytes, and bytearray?
  5. How does Python handle integer overflow?
  6. What is the difference between True/False and 1/0 in Python?
  7. What is type casting? How do you convert between types?
  8. What is id() in Python? What does it return?
  9. What is integer caching (interning) in Python? (caches -5 to 256)
  10. What is string interning in Python?

🔹 Operators

  1. What are Python's arithmetic operators?
  2. What is the difference between / and // in Python?
  3. What is the % operator? What is it used for beyond modulo?
  4. What is the ** operator?
  5. What are comparison operators and what do they return?
  6. What are Python's logical operators (and, or, not)? How do they short-circuit?
  7. What are bitwise operators in Python? (&, |, ^, ~, <<, >>)
  8. What is the walrus operator (:=)? Give a use case.
  9. What are augmented assignment operators?
  10. What is operator precedence in Python?

🔹 Control Flow

  1. What is the difference between if, elif, and else?
  2. What is a ternary expression in Python?
  3. What is the difference between for and while loops?
  4. What is the else clause on a for or while loop? When does it execute?
  5. What is break, continue, and pass?
  6. What is range()? How is it memory efficient?
  7. What is enumerate()? Why is it preferred over using an index?
  8. What is zip()? What happens if the iterables are of different lengths?
  9. What is reversed()? How is it different from [::-1]?
  10. What is sorted() vs .sort()? What is the key argument?

🔹 Strings

  1. Is a Python string mutable or immutable?
  2. What is string slicing? Give examples including step slicing.
  3. What are f-strings? How do they compare to .format() and % formatting?
  4. What is the difference between split() and rsplit()?
  5. What is join()? Why is it preferred over string concatenation in a loop?
  6. What are common string methods: strip(), lstrip(), rstrip(), replace(), find(), count(), startswith(), endswith()?
  7. What is encode() and decode() in Python strings?
  8. What is a raw string (r"...")? When do you use it?
  9. What is string multiplication and string addition?
  10. How does Python handle Unicode strings?

5. Python — Data Structures & Collections

🔹 Lists

  1. How is a Python list stored in memory?
  2. What is the time complexity of common list operations: append, insert, delete, search, access by index?
  3. What is the difference between append() and extend()?
  4. What is list.copy() vs list[:] vs copy.copy()?
  5. What is list.pop() vs del list[i] vs list.remove()?
  6. How does sort() work internally? What algorithm does Python use? (Timsort)
  7. What is list.index() vs list.count()?
  8. What is a 2D list? How do you create and access elements?
  9. How do you flatten a nested list in Python?
  10. What is the difference between list * n and [list] * n? (shallow copy trap)

🔹 Tuples

  1. What is a tuple? How is it different from a list?
  2. Can you modify elements inside a tuple? What about mutable elements inside a tuple?
  3. What is tuple unpacking? Give examples.
  4. What is the * operator in tuple unpacking?
  5. What is a named tuple? How do you create one?
  6. Why are tuples faster than lists?
  7. When should you use a tuple over a list?
  8. What is a single-element tuple? What is the syntax pitfall?
  9. How do you convert a list to a tuple and vice versa?
  10. Can tuples be used as dictionary keys? Why?

🔹 Dictionaries

  1. How is a Python dictionary implemented internally? (hash table)
  2. What is the time complexity of dictionary operations (get, set, delete)?
  3. What is the difference between dict.get() and dict[key]?
  4. What is dict.setdefault()?
  5. What is collections.defaultdict? Give a use case.
  6. What is collections.OrderedDict? Is it still necessary in Python 3.7+?
  7. What is collections.Counter? Give a use case.
  8. What are dictionary views: keys(), values(), items()?
  9. How do you merge two dictionaries? (multiple ways: |, update(), **unpacking)
  10. What is a dictionary comprehension?
  11. What is dict.update()?
  12. What is dict.pop() vs del dict[key]?
  13. What is dict.fromkeys()?
  14. How do you sort a dictionary by value?
  15. What is a nested dictionary? How do you safely access nested keys?

🔹 Sets

  1. What is a Python set? What are its properties?
  2. What is the time complexity of in for a set vs a list?
  3. What are set operations: union (|), intersection (&), difference (-), symmetric difference (^)?
  4. What is the difference between set.discard() and set.remove()?
  5. What is a frozenset? How is it different from a set?
  6. Can a set contain another set? What about a list? Why?
  7. What is set.update() vs |=?
  8. How do you find common elements between two lists efficiently?
  9. What is set.issubset() and set.issuperset()?
  10. How do you remove duplicates from a list using a set?

🔹 Collections Module

  1. What is collections.deque? Why is it better than a list for queues?
  2. What is the time complexity of deque.appendleft() vs list.insert(0, x)?
  3. What is collections.ChainMap?
  4. What is collections.namedtuple vs a regular tuple vs a dataclass?
  5. What is collections.UserDict, UserList, UserString and when do you use them?

6. Python — Functions & Functional Programming

🔹 Function Basics

  1. How do you define a function in Python?
  2. What is the difference between a parameter and an argument?
  3. What are default arguments? What is the mutable default argument trap?
  4. What is *args? How is it different from a list parameter?
  5. What is **kwargs? How is it different from a dict parameter?
  6. What is the order of parameters: positional, *args, keyword-only, **kwargs?
  7. What is a keyword-only argument (parameters after *)?
  8. What is a positional-only argument (parameters before /)? (Python 3.8+)
  9. What is the return statement? Can a function return multiple values?
  10. What happens if a function has no return statement?

🔹 Scope & Closures

  1. What is the LEGB rule in Python (Local, Enclosing, Global, Built-in)?
  2. What is the global keyword? When would you use it?
  3. What is the nonlocal keyword? Give a use case.
  4. What is a closure in Python?
  5. What is a free variable?
  6. How do closures capture variables? What is the late binding problem?
  7. Write a counter function using closures.
  8. What is the difference between a closure and a class?
  9. What is a first-class function in Python?
  10. What is a higher-order function?

🔹 Lambda & Functional Tools

  1. What is a lambda function? What are its limitations?
  2. What is map()? Give an example.
  3. What is filter()? Give an example.
  4. What is reduce() from functools? Give an example.
  5. What is functools.partial()? Give a use case.
  6. What is functools.lru_cache()? How does it work?
  7. What is functools.wraps()? Why is it needed in decorators?
  8. What is functools.total_ordering()?
  9. What is functools.cache() vs lru_cache()?
  10. What is operator module? Give examples of operator.itemgetter and operator.attrgetter.

🔹 Recursion

  1. What is recursion? What is a base case?
  2. What is the maximum recursion depth in Python? How do you change it?
  3. What is tail recursion? Does Python optimize tail calls?
  4. Write a recursive function for factorial.
  5. Write a recursive function for Fibonacci. What is its time complexity?
  6. What is memoization? How does it improve recursive functions?
  7. What is the difference between recursion and iteration?
  8. What is mutual recursion?
  9. What is a recursive data structure?
  10. When should you avoid recursion in Python?

7. Python — OOP (Object-Oriented Programming)

🔹 Classes & Objects

  1. What is the difference between a class and an object (instance)?
  2. What is self? Why is it the first parameter of instance methods?
  3. What is __init__? How is it different from __new__?
  4. What are class variables vs instance variables? What happens when they share a name?
  5. What is __dict__ on a class and on an instance?
  6. What is vars() in Python?
  7. What is dir() in Python?
  8. What is hasattr(), getattr(), setattr(), delattr()?
  9. How do you check if an object is an instance of a class? (isinstance())
  10. How do you check if a class is a subclass of another? (issubclass())

🔹 The Four Pillars

  1. What is Encapsulation? How do you implement it in Python?
  2. What is the difference between _name (convention), __name (name mangling), and __name__ (dunder)?
  3. What is Abstraction? How does it differ from encapsulation?
  4. What is Inheritance? Give an example.
  5. What is single vs multiple inheritance in Python?
  6. What is the MRO (Method Resolution Order)? What is the C3 linearization algorithm?
  7. How do you find the MRO of a class? (ClassName.__mro__ or mro())
  8. What is Polymorphism? Give a Python example.
  9. What is method overriding? How does it work in Python?
  10. Does Python support method overloading? How do you simulate it?

🔹 Special / Dunder Methods

  1. What is __str__ vs __repr__? Which is called in which situation?
  2. What is __len__?
  3. What is __getitem__, __setitem__, __delitem__?
  4. What is __iter__ and __next__?
  5. What is __contains__ (enables in operator)?
  6. What is __call__? How do you make an object callable?
  7. What is __eq__, __lt__, __gt__, __le__, __ge__, __ne__?
  8. What is __add__, __sub__, __mul__, __truediv__? (operator overloading)
  9. What is __enter__ and __exit__? (context manager protocol)
  10. What is __slots__? What are its advantages and limitations?
  11. What is __init_subclass__? Give a use case.
  12. What is __del__? When is it called? Is it reliable?
  13. What is __hash__? What is the relationship between __eq__ and __hash__?
  14. What is __bool__? When is it called vs __len__?
  15. What is __missing__ in a dict subclass?

🔹 Class Methods & Properties

  1. What is @staticmethod? When would you use it?
  2. What is @classmethod? When would you use it?
  3. What is the difference between @staticmethod and @classmethod?
  4. What is @property? What is a getter and setter in Python?
  5. What is a @property.setter and @property.deleter?
  6. When would you use a property vs a regular method?
  7. What is a class factory method? Give an example.
  8. What is __new__ used for? Give a practical example (e.g., Singleton).
  9. What is type() used as a metaclass? How do you create a class dynamically?
  10. What is object.__class__?

🔹 Inheritance & Advanced OOP

  1. What is super()? How does it work with multiple inheritance?
  2. What is a mixin? Give a real-world use case.
  3. What is composition vs inheritance? When do you prefer composition?
  4. What is an abstract class? How do you create one using the abc module?
  5. What is @abstractmethod? What happens if you don't implement it?
  6. What is the difference between an abstract class and an interface (Protocol)?
  7. What is typing.Protocol? How is it used for structural subtyping?
  8. What is a dataclass (@dataclass)? What does it auto-generate?
  9. What are the parameters of @dataclass: frozen, order, eq, repr?
  10. What is field() in dataclasses? What is default_factory?
  11. What is __post_init__ in dataclasses?
  12. What is NamedTuple vs dataclass vs regular class?
  13. What is the Enum class? How do you define an enumeration?
  14. What is IntEnum, StrEnum, Flag, IntFlag?
  15. What is a descriptor in Python? What are __get__, __set__, __delete__?

🔹 Design Patterns

  1. Implement the Singleton pattern in Python (at least 2 ways).
  2. Implement the Factory pattern in Python.
  3. Implement the Abstract Factory pattern.
  4. Implement the Observer pattern in Python.
  5. Implement the Strategy pattern in Python.
  6. Implement the Decorator design pattern (not Python @decorator) in Python.
  7. Implement the Command pattern in Python.
  8. Implement the Iterator pattern using __iter__ and __next__.
  9. What is dependency injection? Give a Python example.
  10. What is the Repository pattern and why is it used with databases?

8. Python — Modules, Packages & Imports

🔹 Modules & Packages

  1. What is a module in Python?
  2. What is a package? What is __init__.py? What is a namespace package?
  3. What is the difference between import module and from module import name?
  4. What is import *? Why is it discouraged?
  5. What is __all__ in a module?
  6. What is a relative import vs absolute import?
  7. What is importlib? How do you import a module dynamically?
  8. What is sys.path? How does Python find modules?
  9. What is __name__ == "__main__"? Why is it used?
  10. What is the difference between a script and a module?
  11. What is __file__ in a module?
  12. How do you reload a module at runtime?
  13. What is a circular import? How do you resolve it?
  14. What is a virtual environment? Why is it important?
  15. What is __package__ attribute?

🔹 Package Management

  1. What is pip? How do you install, uninstall, upgrade, and list packages?
  2. What is requirements.txt? How do you generate it?
  3. What is the difference between pip install and pip install -e (editable mode)?
  4. What is pyproject.toml? How is it different from setup.py?
  5. What is venv vs virtualenv vs conda?

9. Python — File Handling & I/O

🔹 File Operations

  1. How do you open a file in Python? What are the different modes (r, w, a, rb, wb, r+)?
  2. What is the with statement for file handling? Why is it preferred?
  3. What is the difference between read(), readline(), and readlines()?
  4. What is the difference between write() and writelines()?
  5. What is seek() and tell()?
  6. How do you check if a file exists?
  7. How do you copy, move, rename, and delete files in Python?
  8. What is os.path vs pathlib.Path? Which is preferred and why?
  9. How do you list files in a directory? How do you walk a directory tree?
  10. What is glob? Give a use case.
  11. How do you read a large file line by line without loading it into memory?
  12. What is tempfile module? When do you use it?
  13. What is shutil? What can it do?
  14. How do you work with CSV files in Python? (csv module)
  15. How do you work with JSON files in Python?

🔹 Serialization

  1. What is pickle? What are the security risks of using it?
  2. What is json.dumps() vs json.dump()? What is the difference?
  3. What is json.loads() vs json.load()?
  4. What is the indent and separators argument in json.dumps()?
  5. What is shelve? When would you use it?

10. Python — Error & Exception Handling

🔹 Exception Basics

  1. What is an exception in Python? How is it different from a syntax error?
  2. What is the difference between Exception and BaseException?
  3. What are built-in exceptions? Name at least 15. (ValueError, TypeError, KeyError, IndexError, AttributeError, NameError, ImportError, OSError, RuntimeError, StopIteration, NotImplementedError, ZeroDivisionError, OverflowError, MemoryError, RecursionError)
  4. What is the exception hierarchy in Python?
  5. What is try, except, else, finally?
  6. What is the else clause in a try block? When does it run?
  7. What is the finally clause? Does it always execute?
  8. Can you have multiple except blocks? Can you catch multiple exceptions in one block?
  9. What is the order of except blocks? Does it matter? (more specific first)
  10. What is a bare except:? Why is it dangerous?

🔹 Raising & Custom Exceptions

  1. What is raise? How do you re-raise the current exception?
  2. What is raise ... from ...? What does it do to the traceback?
  3. How do you create a custom exception class?
  4. What is exception chaining? What is __cause__ and __context__?
  5. What is warnings module? How is it different from exceptions?
  6. What is contextlib.suppress()?
  7. What is ExceptionGroup in Python 3.11+?
  8. What is except* syntax in Python 3.11+?
  9. What is sys.exc_info()?
  10. Best practices: When should you catch exceptions broadly vs specifically?

11. Python — Iterators, Generators & Comprehensions

🔹 Iterators & Iterables

  1. What is an iterable? What is an iterator?
  2. What is the iterator protocol? (__iter__ and __next__)
  3. What is StopIteration? How is it raised?
  4. What is the difference between calling iter() and next() built-ins?
  5. What is lazy evaluation? How do iterators implement it?
  6. What is itertools module? Name at least 10 functions from it.
  7. What is itertools.chain()?
  8. What is itertools.islice()?
  9. What is itertools.product()?
  10. What is itertools.groupby()? What is its sorting requirement gotcha?
  11. What is itertools.cycle()?
  12. What is itertools.accumulate()?
  13. What is itertools.combinations() vs itertools.permutations()?
  14. What is itertools.zip_longest()?
  15. What is itertools.starmap()?

🔹 Generators

  1. What is a generator function? What makes it a generator?
  2. What is yield? How is it different from return?
  3. What is yield from? Give a use case.
  4. What is a generator expression? How does it differ from a list comprehension?
  5. How does send() work on a generator?
  6. How does throw() work on a generator?
  7. How does close() work on a generator? What exception is raised internally? (GeneratorExit)
  8. What are the states of a generator? (created, running, suspended, closed)
  9. What are the memory advantages of generators over lists?
  10. Write an infinite generator for Fibonacci numbers.
  11. What is next() with a default value?
  12. Write a generator pipeline for processing large files.
  13. What is inspect.isgenerator() vs inspect.isgeneratorfunction()?
  14. What is types.GeneratorType?
  15. How do you convert a generator to a list? What are the implications?

🔹 Comprehensions

  1. What is a list comprehension? What is its syntax?
  2. What is a dictionary comprehension?
  3. What is a set comprehension?
  4. What is a generator expression vs a list comprehension?
  5. Can you have nested comprehensions? Give an example.
  6. What are the performance implications of list comprehensions vs for loops?
  7. What is a conditional comprehension (with if clause as filter)?
  8. 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)]?
  9. When should you NOT use a comprehension?
  10. What is variable leaking in Python 2 list comprehensions vs Python 3?

12. Python — Decorators & Context Managers

🔹 Decorators

  1. What is a decorator in Python?
  2. How do you write a simple function decorator?
  3. What is functools.wraps()? Why must you use it in decorators?
  4. What is a decorator with arguments? How do you write one (decorator factory)?
  5. What is a class-based decorator? How does __call__ enable it?
  6. What is the order of stacked decorators? Which applies first?
  7. Write a decorator that measures function execution time.
  8. Write a decorator that retries a function on exception (with max retries).
  9. Write a decorator that caches function results (manual lru_cache).
  10. Write a decorator that validates function argument types.
  11. What is @staticmethod, @classmethod, @property — are these decorators?
  12. What is @functools.lru_cache? What are maxsize and typed parameters?
  13. What is @functools.cached_property? How is it different from @property?
  14. What is a parametrized decorator factory?
  15. What are real-world use cases for decorators? (logging, auth, rate limiting, caching, timing)

🔹 Context Managers

  1. What is a context manager? What protocol does it use?
  2. What is __enter__ and __exit__?
  3. What do the arguments of __exit__(exc_type, exc_val, exc_tb) mean?
  4. How do you suppress an exception inside __exit__?
  5. What is contextlib.contextmanager? How do you write a generator-based context manager?
  6. What is contextlib.suppress()?
  7. What is contextlib.ExitStack()? When is it useful?
  8. What is contextlib.asynccontextmanager?
  9. Write a context manager for timing code execution.
  10. Write a context manager that manages a database connection.

13. Python — Concurrency & Parallelism

🔹 Core Concepts

  1. What is the difference between concurrency and parallelism?
  2. What is a process vs a thread?
  3. What is the GIL (Global Interpreter Lock) in Python? Why does it exist?
  4. How does the GIL affect CPU-bound vs I/O-bound programs?
  5. When does the GIL not matter?
  6. What is threading module vs multiprocessing module? When do you use each?
  7. What is asyncio? How is it different from threading?
  8. What is an event loop in asyncio?
  9. What is async and await? How do they work?
  10. What is a coroutine in Python?

🔹 Threading

  1. How do you create and start a thread in Python?
  2. What is threading.Thread? What are the target, args, kwargs, daemon parameters?
  3. What is a daemon thread? What happens when the main thread exits?
  4. What is thread safety? How do you make code thread-safe?
  5. What is a Lock in threading?
  6. What is RLock (Reentrant Lock)? When do you need it over a regular Lock?
  7. What is a Semaphore? What is BoundedSemaphore?
  8. What is threading.Event? Give a use case.
  9. What is threading.Condition? Give a producer-consumer example.
  10. What is threading.Barrier?
  11. What is threading.Timer?
  12. What is threading.local()? When would you use thread-local storage?
  13. What is a race condition? Give a Python threading example.
  14. What is a deadlock? Give a Python threading deadlock example.
  15. What is thread starvation?
  16. What is the producer-consumer problem? How do you solve it in Python?
  17. What is queue.Queue? How is it thread-safe?
  18. What is queue.LifoQueue vs queue.PriorityQueue?
  19. How do you join threads? What does thread.join() do?
  20. What is threading.active_count() and threading.enumerate()?

🔹 Multiprocessing

  1. What is multiprocessing.Process? How is it different from threading.Thread?
  2. How do processes share memory? What about threads?
  3. What is multiprocessing.Pool? What methods does it offer?
  4. What is the difference between Pool.map(), Pool.starmap(), Pool.apply(), Pool.apply_async()?
  5. What is multiprocessing.Queue? How is it different from queue.Queue?
  6. What is multiprocessing.Pipe? What is the difference between send() and recv()?
  7. What is multiprocessing.Value and multiprocessing.Array? (shared memory)
  8. What is multiprocessing.Manager? What objects does it support?
  9. What is multiprocessing.Lock() vs threading.Lock()?
  10. What is the difference between fork, spawn, and forkserver start methods?
  11. Why is if __name__ == '__main__' required in multiprocessing?
  12. What is concurrent.futures.ProcessPoolExecutor?
  13. What is concurrent.futures.ThreadPoolExecutor?
  14. What is executor.submit() vs executor.map()?
  15. What is a Future object in concurrent.futures?
  16. What is as_completed() in concurrent.futures?
  17. What is wait() in concurrent.futures?
  18. What is chunksize in Pool.map()? Why does it matter for performance?
  19. How do you handle exceptions in child processes?
  20. What is multiprocessing.cpu_count()?

🔹 Asyncio & Async Programming

  1. What is asyncio.run()?
  2. What is asyncio.create_task()? How is it different from await coroutine?
  3. What is asyncio.gather()? How does it handle exceptions?
  4. What is asyncio.wait() vs asyncio.gather()?
  5. What is asyncio.sleep()? Why not time.sleep() in async code?
  6. What is asyncio.Queue?
  7. What is asyncio.Lock(), asyncio.Semaphore(), asyncio.Event()?
  8. What is asyncio.shield()? When is it useful?
  9. How do you run a blocking (synchronous) function inside an async program?
  10. What is loop.run_in_executor()?
  11. What is asyncio.timeout() / asyncio.wait_for()?
  12. What is aiohttp? How does it differ from requests?
  13. What is the difference between a coroutine object and a task?
  14. How do you cancel an asyncio task?
  15. What is asyncio.current_task() and asyncio.all_tasks()?
  16. What are task groups (asyncio.TaskGroup) in Python 3.11+?
  17. What is structured concurrency?

🔹 Scenario / Real-World Questions

  1. Scenario: You are building a web scraper that needs to scrape 10,000 URLs. Would you use threading, multiprocessing, or asyncio? Why?
  2. Scenario: You have a CPU-intensive image processing task across 1 million images. Which approach do you choose?
  3. Scenario: You need to make 1000 HTTP API requests as fast as possible. Which approach gives the best performance?
  4. Scenario: Describe a real-world deadlock scenario in a web application and how you would prevent it.
  5. Scenario: Two threads are incrementing a shared counter. The result is always less than expected. Why? How do you fix it?
  6. 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

  1. How does Python manage memory?
  2. What is reference counting in Python?
  3. What is the garbage collector in Python? When does it run?
  4. What is a reference cycle? Give an example.
  5. What is gc module? What does gc.collect() do?
  6. What is sys.getrefcount()? Why does it always return at least 1?
  7. What is __del__? Is it reliable? Why or why not?
  8. What is weakref? When would you use a weak reference?
  9. What is a memory leak in Python? How can it happen?
  10. What is tracemalloc? How do you use it to track memory usage?
  11. What is sys.getsizeof()? What are its limitations?
  12. What is the small object allocator (pymalloc) in CPython?
  13. How do __slots__ reduce memory usage?
  14. What is the difference between stack memory and heap memory in Python?
  15. What is memory fragmentation in Python?

🔹 Python Internals

  1. What is Python bytecode? How do you view it?
  2. What is the dis module?
  3. What is the CPython interpreter?
  4. What are the alternatives to CPython? (PyPy, Jython, IronPython, MicroPython)
  5. What is PyPy? How is it faster than CPython? (JIT compilation)
  6. What is ctypes? How can you call C functions from Python?
  7. How does Python's int object handle arbitrarily large integers?
  8. What is integer caching in CPython? Which integers are cached?
  9. What is string interning? Which strings are automatically interned?
  10. What is __pycache__? What is the .pyc file format?

15. Python — Standard Library & Useful Modules

🔹 Must-Know Modules

  1. What is os module? Name 10 commonly used functions/attributes.
  2. What is sys module? Name 5 commonly used attributes.
  3. What is pathlib? How is it different from os.path?
  4. What is datetime module? How do you get the current date and time?
  5. What is the difference between datetime.date, datetime.time, and datetime.datetime?
  6. What is timedelta? Give a use case.
  7. What is time.time() vs time.perf_counter() vs time.process_time()?
  8. What is random module? Name 5 commonly used functions.
  9. What is math module? Name 5 commonly used functions.
  10. What is statistics module? What functions does it provide?
  11. What is the re module? What are re.match(), re.search(), re.findall(), re.sub(), re.split()?
  12. What is the difference between re.match() and re.search()?
  13. What are groups in regex? What is re.group() and named groups?
  14. What is a compiled regex pattern? Why use re.compile()?
  15. What is hashlib? Name common hash algorithms and give a use case.
  16. What is uuid module? What is the difference between UUID1, UUID4, UUID5?
  17. What is base64 encoding? How do you encode/decode?
  18. What is io module? What is StringIO and BytesIO?
  19. What is logging module? How do you set up basic and advanced logging?
  20. What are logging levels? (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  21. What is a logging handler? What is a logging formatter? What is a logging filter?
  22. What is argparse? How do you parse command-line arguments?
  23. What is configparser? How do you read .ini files?
  24. What is subprocess? How do you run a shell command from Python?
  25. What is subprocess.run() vs subprocess.Popen()?
  26. What is socket module? What is TCP vs UDP?
  27. What is copy module? What is copy.copy() vs copy.deepcopy()?
  28. What is pprint? When do you use it?
  29. What is decimal module? Why use it over float? (floating point precision)
  30. What is fractions module?
  31. What is heapq module? Name its key functions.
  32. What is bisect module? What are bisect_left() and bisect_right()?
  33. What is array module? How is it different from a list?
  34. What is struct module? When is it used?
  35. What is textwrap module?
  36. What is difflib module?
  37. What is calendar module?
  38. What is zlib and gzip module?
  39. What is tarfile and zipfile module?
  40. What is sqlite3 module?

16. Python — Type Hints & Annotations

🔹 Type Hints Basics

  1. What are type hints in Python? Are they enforced at runtime?
  2. What is the typing module?
  3. What is Optional[T]? How is it different from Union[T, None]?
  4. What is Union[T1, T2]? What is T1 | T2 syntax (Python 3.10+)?
  5. What is List[T], Dict[K, V], Tuple[T, ...], Set[T]?
  6. What is Any type? When would you use it?
  7. What is Callable[[args], return_type]?
  8. What is TypeVar? How is it used for generic functions?
  9. What is Generic[T]? How do you write a generic class?
  10. What is Protocol? How is it used for structural typing (duck typing with types)?
  11. What is TypedDict?
  12. What is Final? How does it signal a constant?
  13. What is Literal? Give a use case.
  14. What is ClassVar?
  15. What is overload decorator in typing?
  16. What is mypy? How do you use it?
  17. What is pyright? How is it different from mypy?
  18. What is TYPE_CHECKING? Why is it used?
  19. What are forward references (string annotations) in type hints?
  20. What is get_type_hints()?

17. Python — Testing

🔹 Testing Fundamentals

  1. What is unit testing vs integration testing vs end-to-end testing?
  2. What is unittest module? How do you write a test case?
  3. What is setUp() and tearDown() in unittest?
  4. What is setUpClass() and tearDownClass()?
  5. What is pytest? How is it different from unittest?
  6. What are pytest fixtures? How are they different from setUp/tearDown?
  7. What is fixture scope in pytest? (function, class, module, session)
  8. What is pytest.mark.parametrize?
  9. What is pytest.raises? How do you test for exceptions?
  10. What is pytest.warns?
  11. What is mocking in Python testing?
  12. What is unittest.mock.Mock?
  13. What is unittest.mock.MagicMock?
  14. What is @patch decorator? What does it replace?
  15. What is patch.object()?
  16. What is side_effect in Mock? How is it different from return_value?
  17. What is assert_called_once_with()?
  18. What is code coverage? How do you measure it with pytest-cov?
  19. What is TDD (Test-Driven Development)?
  20. What is property-based testing? What is hypothesis library?

18. Python — Database Integration

🔹 Working with Databases

  1. What is psycopg2? How do you connect to PostgreSQL from Python?
  2. What is a connection vs a cursor in database programming?
  3. What is cursor.execute() vs cursor.executemany()?
  4. What is a parameterized query? Why is it important for SQL injection prevention?
  5. What is connection.commit() vs connection.rollback()?
  6. What is pymongo? How do you connect to MongoDB from Python?
  7. What is SQLAlchemy? What are its two main components?
  8. What is SQLAlchemy Core vs SQLAlchemy ORM?
  9. What is a SQLAlchemy Session?
  10. What is declarative_base() in SQLAlchemy?
  11. What are SQLAlchemy relationships? (relationship(), ForeignKey)
  12. What is lazy loading vs eager loading in SQLAlchemy?
  13. What is Alembic? How do you create and apply migrations?
  14. What is an ORM? What are its advantages and disadvantages?
  15. What is connection pooling in SQLAlchemy?

19. Python — Web & APIs

🔹 Web Frameworks & HTTP

  1. What is requests library? How do you make a GET and POST request?
  2. What is requests.Session()? What are its advantages?
  3. What are request headers, query params, and request body?
  4. What is requests.Response? What are status_code, text, json(), content?
  5. What is httpx? How is it different from requests?
  6. What is aiohttp? Why is it used with asyncio?
  7. What is REST? What are the HTTP methods and their semantic meanings?
  8. What is Flask? Write a simple Hello World API in Flask.
  9. What is FastAPI? What makes it fast? (Starlette + Pydantic + async)
  10. What is Django? How is it different from Flask and FastAPI?
  11. What is middleware in web frameworks?
  12. What is WSGI vs ASGI?
  13. What is Pydantic? How is it used for data validation in FastAPI?
  14. What is dependency injection in FastAPI?
  15. What is uvicorn? What role does it play?

20. Python — Advanced Topics

🔹 Metaclasses

  1. What is a metaclass in Python?
  2. What is type? How is it the metaclass of all classes?
  3. How do you create a custom metaclass?
  4. What are __prepare__, __new__, __init__ hooks in a metaclass?
  5. What is __init_subclass__? How is it used as a simpler alternative to metaclasses?
  6. What is abc.ABCMeta?
  7. What is the difference between a class decorator and a metaclass?
  8. What are real-world use cases for metaclasses? (ORMs, plugin systems, validation)
  9. What is type.__new__() vs object.__new__()?
  10. What is __class_getitem__ used for?

🔹 Descriptors

  1. What is a descriptor in Python?
  2. What is the difference between a data descriptor and a non-data descriptor?
  3. What is __get__, __set__, __delete__ in a descriptor?
  4. How does @property use the descriptor protocol?
  5. How do classmethod and staticmethod use descriptors internally?

🔹 Advanced Python Features

  1. What is __getattr__ vs __getattribute__? What is the difference?
  2. What is __set_name__? Give a use case.
  3. What is structural pattern matching (match/case) in Python 3.10+?
  4. What is TypeAlias in Python 3.10+?
  5. What is ParamSpec in typing? Give a use case.
  6. What is Self type in Python 3.11+?
  7. What is LiteralString in Python 3.11+?
  8. What is zoneinfo module?
  9. What is graphlib in Python 3.9+?
  10. What is the ast module? How do you parse Python source code?
  11. What is inspect module? Name 5 use cases.
  12. What is dis module? How do you disassemble Python bytecode?
  13. What is cProfile? How do you profile a Python script?
  14. What is line_profiler? How is it more granular than cProfile?
  15. What is Cython? How does it speed up Python?

21. System Design / Architecture Questions

(Based on real interview experience — these come up often)

  1. 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?

  2. 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)
  3. PostgreSQL vs MySQL: Both are relational — why would you pick PostgreSQL over MySQL? What about the reverse?

  4. CAP Theorem: What is the CAP theorem? Where do PostgreSQL and MongoDB fit?

  5. ACID vs BASE: What is the difference? Which databases follow which model?

  6. 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.

  7. Scaling: How do you scale a PostgreSQL database? What about a MongoDB cluster?

  8. Caching: When would you add a cache (like Redis) in front of a database?

  9. Sharding vs Replication: What is the difference? When do you use each?

  10. 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)

  1. 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?
  2. What is the difference between a stack and a queue? Implement both using Python lists.
  3. What is a linked list? Implement reverse() on a singly linked list.
  4. What is the difference between BFS and DFS? When do you use each?
  5. What is a binary search tree? What are its time complexities for insert, search, and delete?
  6. What is a hash table? How does Python's dictionary implement it internally?
  7. What is the two-pointer technique? Give an example problem.
  8. What is dynamic programming? Explain with the Fibonacci and knapsack example.
  9. Write a function to check if a string is a palindrome.
  10. What is the sliding window technique? Give an example.
  11. What is a heap? What is heapq in Python?
  12. What is the time complexity of sorting algorithms: Bubble, Selection, Insertion, Merge, Quick, Heap, Tim?
  13. Scenario: Given a list of integers, find all pairs that sum to a target value. What is the optimal approach?
  14. What is a trie? When would you use one?
  15. What is a graph? Explain adjacency list vs adjacency matrix representation.
  16. What is Dijkstra's algorithm? What data structure does it use?
  17. What is a topological sort? When is it used?
  18. What is a union-find (disjoint set) data structure?
  19. What is the difference between a min-heap and a max-heap?
  20. What is an LRU cache? Implement it in Python using OrderedDict.

Top comments (0)