Python Interview Questions (60+ Deep Dive Q&A)
1. Core Language & Data Structures
1. Python Memory Management (The 3 Pillars)
1. Python Memory Management (The 3 Pillars)
- Private Heap: Where all objects/data live. Managed by Memory Manager.
- Raw Memory Allocator: Interaction with OS (malloc).
- Object-Specific Allocators: Pymalloc (for small objects < 512 bytes). Optimize fragmentation. Garbage Collection: Reference Counting (Primary) + Cyclic GC (Secondary).
2. List vs Tuple vs Set vs Dictionary
2. List vs Tuple vs Set vs Dictionary
| Type | Mutable | Ordered | Allow Duplicates | Lookup Cost |
|---|---|---|---|---|
| List | Yes | Yes | Yes | O(N) |
| Tuple | No | Yes | Yes | O(N) |
| Set | Yes | No | No | O(1) |
| Dict | Yes | Yes (3.7+) | Keys: No | O(1) |
3. `__init__` vs `__new__` (Diagram)
3. `__init__` vs `__new__` (Diagram)
__new__: The Allocating phase. Returns the object. (Static method).__init__: The Initializing phase. Sets attributes. (Instance method). Flow:Class()call ->__new__-> creates instance ->__init__(instance)-> sets props.
4. MRO (Method Resolution Order)
4. MRO (Method Resolution Order)
ClassName.mro() or help(ClassName) calls show the order.Diamond Problem Example:5. Decorators (Internals)
5. Decorators (Internals)
wraps the target.6. Generators vs Iterators
6. Generators vs Iterators
- Iterator: Class with
__next__and__iter__. State managed manually. - Generator: Function with
yield. State managed auto. Pauses execution. High memory efficiency.
7. Context Managers (The `with` statement)
7. Context Managers (The `with` statement)
__enter__ (setup) and __exit__ (teardown).
Exception Handling: __exit__ receives exception details. Return True to suppress.8. Lambdas
8. Lambdas
lambda x: x * 2.
Limited: No statements (assignment, while), only expressions.
Used often with map, filter, sort(key=...).9. `*args` and `**kwargs`
9. `*args` and `**kwargs`
*args: Tuple of positional args.**kwargs: Dictionary of keyword args. Unpacking:func(*my_list)expands list into args.
10. Shallow vs Deep Copy
10. Shallow vs Deep Copy
2. Advanced OOP
11. Encapsulation (Public, Protected, Private)
11. Encapsulation (Public, Protected, Private)
name: Public._name: Protected (Convention only). “Internal use”.__name: Private (Name Mangling). Becomes_Class__name. Harder to access. python has no strict enforcement (we are all consenting adults).
12. Abstract Base Classes (ABC)
12. Abstract Base Classes (ABC)
Animal. Subclass MUST implement speak.13. `__slots__` Optimization
13. `__slots__` Optimization
__dict__ (dynamic). Uses RAM.
__slots__ = ['x', 'y'] tells Python “This class ONLY has x and y”.
Allocates fixed array. Saves memory for millions of objects.14. Property Decorators (Getters/Setters)
14. Property Decorators (Getters/Setters)
obj.age (looks like attribute, runs like method).15. Duck Typing vs Static Typing
15. Duck Typing vs Static Typing
- Duck: “If it has
quack(), it’s a Duck”. Runtime check. - Static (Hints):
def quack(d: Duck) -> None:. Analysis tool check (Mypy).
16. Composition vs Inheritance
16. Composition vs Inheritance
- Inheritance: “Is-A”.
Caris aVehicle. Rigid. - Composition: “Has-A”.
Carhas anEngine. Flexible. Prefer Composition to avoid Deep Inheritance hierarchies (Fragile Base Class problem).
17. Method Overloading?
17. Method Overloading?
- Default args (
def f(a, b=None)). *args.@functools.singledispatch.
18. Singletons
18. Singletons
- Module: Modules are singletons.
__new__: Checkif cls._instance is None.- Decorator: Wrap class.
19. Enum Class
19. Enum Class
from enum import Enum.
Immutable constants.
Color.RED is distinct from string “RED” and int 1.20. Dataclasses (3.7+)
20. Dataclasses (3.7+)
__init__, __repr__, __eq__.3. Asyncio & Concurrency
21. Threading vs Multiprocessing vs Asyncio
21. Threading vs Multiprocessing vs Asyncio
- Threading: OS Threads. 1 CPU core (GIL). Good for I/O blocking (Network).
- Multiprocessing: OS Processes. All cores. Good for CPU Heavy. High overhead.
- Asyncio: Single Thread. Cooperative Multitasking. Good for Massive I/O (10k connections).
22. GIL (Global Interpreter Lock)
22. GIL (Global Interpreter Lock)
- CPU-bound: Use
multiprocessingorasynciowith C extensions - I/O-bound: Use
threadingorasyncio(GIL released during I/O wait)
23. Event Loop Explained
23. Event Loop Explained
async def) yield control (await) when blocked.
Loop runs other tasks.24. `await` keyword
24. `await` keyword
async def.25. Race Conditions in Asyncio?
25. Race Conditions in Asyncio?
awaits, race happens.
Locking is still needed (asyncio.Lock).26. Blocking Code in Async
26. Blocking Code in Async
time.sleep(10) blocks the entire Loop. No other interaction possible.
Fix: await asyncio.sleep(10).
For CPU logic: loop.run_in_executor (Offload to ThreadPool).27. `asyncio.gather`
27. `asyncio.gather`
results = await asyncio.gather(task1(), task2()).28. Async Context Managers
28. Async Context Managers
async with conn.transaction():.
Methods __aenter__ and __aexit__.
Needed for async cleanup (e.g., closing DB pool).29. Async Iterators
29. Async Iterators
async for item in fetch_stream():.
Methods __aiter__ and __anext__.
Used for streaming data.30. UVLoop
30. UVLoop
libuv (Node.js engine).
Makes Python Asyncio 2-4x faster.4. Backend & Web (Django/FastAPI)
31. WSGI vs ASGI
31. WSGI vs ASGI
- WSGI: Sync Standard (Flask, Django). Blocking.
- ASGI: Async Standard (FastAPI, Django Channels). Supports WebSockets, HTTP2.
32. FastAPI Features
32. FastAPI Features
- Speed: Native Async/Starlette.
- Validation: Pydantic models.
- Docs: Auto Swagger/OpenAPI.
- DI: Powerful Dependency Injection system.
33. Django ORM N+1 Problem
33. Django ORM N+1 Problem
for book in books: print(book.author.name).
Fix: select_related (Join / FK) or prefetch_related (M2M / Reverse FK).34. Middleware
34. Middleware
35. CSRF in Django
35. CSRF in Django
csrf_token in POST data matching the cookie.
Prevents external forms from posting to your server.36. Gunicorn vs Uvicorn
36. Gunicorn vs Uvicorn
- Gunicorn: Process Manager. For Production. Spawns workers.
- Uvicorn: ASGI Worker. Runs the Async code.
- Setup: Gunicorn manages Uvicorn workers.
37. REST vs GraphQL
37. REST vs GraphQL
- REST: Multiple endpoints. Fixed structure. Over/Under fetching.
- GraphQL: Single Endpoint. Client defines structure. Exact fetching. Complex caching.
38. DB Migrations
38. DB Migrations
39. Session vs JWT Auth
39. Session vs JWT Auth
- Session: Server stores state (Memory/Redis). Cookie ID. Revocable.
- JWT: Client stores state (Signature). Stateless. Scalable. Hard to revoke.
40. Dependency Injection
40. Dependency Injection
def route(db: Session = Depends(get_db)):.
Unit testing becomes easy (Pass Mock DB).5. Coding Scenarios & Snippets
41. Flatten Nested List (Recursive)
41. Flatten Nested List (Recursive)
42. LRU Cache Implementation (Concept)
42. LRU Cache Implementation (Concept)
@functools.lru_cache.43. Singleton Decorator
43. Singleton Decorator
44. Reverse String (Slicing)
44. Reverse String (Slicing)
s[::-1].
Detailed: s[start:stop:step]. Step -1 implies reverse.45. Find Duplicates
45. Find Duplicates
46. Binary Search (Bisect)
46. Binary Search (Bisect)
import bisect.
bisect.bisect_left(arr, x) returns index.
Array must be sorted.47. Context Manager Class
47. Context Manager Class
48. Merge Dictionaries
48. Merge Dictionaries
z = {**x, **y} or x | y (Py 3.9).49. Reading Huge File
49. Reading Huge File
read(). Use iterator.50. Sort list of dicts by key
50. Sort list of dicts by key
6. Edge Cases & Trivia
51. `is` vs `==`
51. `is` vs `==`
==: Value equality (__eq__).is: Identity equality (Memory Address).a = [1]; b = [1].a == b(True).a is b(False).
52. Mutable Default Args
52. Mutable Default Args
def f(l=[]): l is shared across all calls.
Fix: l=None.53. Python Bytecode
53. Python Bytecode
.py to .pyc (Bytecode). Stack-based VM executes it.
import dis; dis.dis(func).54. `__name__ == '__main__'`
54. `__name__ == '__main__'`
python app.py), not when imported (import app).55. Monkey Patching
55. Monkey Patching
56. `pass` vs `...` (Ellipsis)
56. `pass` vs `...` (Ellipsis)
pass: No-op statement....: Singleton object. Used in Type Hinting (Callable[..., int]) or Slicing.
57. Pickling security
57. Pickling security
58. `__dict__`
58. `__dict__`
obj.x -> obj.__dict__['x'].
Classes using __slots__ don’t have this.59. Python Path
59. Python Path
sys.path. List of directories Python searches for imports.
First entry is current directory.60. PyPy vs CPython
60. PyPy vs CPython
- CPython: Standard interpreter. C. Uses Ref Counting.
- PyPy: JIT Compiler. Fast. Uses Tracing JIT. Bad for C-Extensions (NumPy).
7. Python Medium Level Questions
61. List Comprehensions vs Generator Expressions
61. List Comprehensions vs Generator Expressions
62. Dictionary and Set Comprehensions
62. Dictionary and Set Comprehensions
63. *args and **kwargs Unpacking
63. *args and **kwargs Unpacking
64. Lambda Functions and Functional Programming
64. Lambda Functions and Functional Programming
65. Collections Module
65. Collections Module
66. Itertools Module
66. Itertools Module
67. Functools Module
67. Functools Module
68. String Formatting
68. String Formatting
69. File Handling with Context Manager
69. File Handling with Context Manager
70. Exception Handling
70. Exception Handling
71. Custom Exceptions
71. Custom Exceptions
72. Regular Expressions
72. Regular Expressions
73. Datetime and Timezone
73. Datetime and Timezone
74. Pathlib
74. Pathlib
75. JSON and Pickle
75. JSON and Pickle
76. CSV Parsing
76. CSV Parsing
77. Logging Module
77. Logging Module
78. Enumerate and Zip
78. Enumerate and Zip
79. Any and All
79. Any and All
80. Sorted and Sort
80. Sorted and Sort
8. Python Advanced Level Questions
81. Metaclasses
81. Metaclasses
82. Descriptors
82. Descriptors
83. Abstract Base Classes
83. Abstract Base Classes
84. Type Hints and Typing
84. Type Hints and Typing
85. Generics and TypeVar
85. Generics and TypeVar
86. Asyncio Coroutines
86. Asyncio Coroutines
87. Asyncio Tasks and Futures
87. Asyncio Tasks and Futures
88. Context Variables
88. Context Variables
89. Memory Views
89. Memory Views
90. C Extensions with ctypes
90. C Extensions with ctypes
91. Profiling with cProfile
91. Profiling with cProfile
92. Memory Profiling
92. Memory Profiling
93. Debugging with pdb
93. Debugging with pdb
94. Import System and importlib
94. Import System and importlib
95. Slots for Memory Optimization
95. Slots for Memory Optimization
96. Property Decorators Advanced
96. Property Decorators Advanced
97. Dataclasses
97. Dataclasses
98. Protocol Classes
98. Protocol Classes
99. AST Manipulation
99. AST Manipulation
100. Bytecode Inspection
100. Bytecode Inspection