QA
🐍
Backend

Python Interview Questions

Python interview questions spanning core syntax, dunder methods, GIL trade-offs, asyncio event loop, FastAPI/Django patterns, and profiling.

🎯 Ready to test your knowledge?

Take Python Skill Assessment Quiz

First prepare from the 100 learning questions below, then test your skills with 15 random MCQs categorized into Beginner, Intermediate, and Senior levels.

Launch 15-MCQ Quiz →
Experience Level:

Showing 100 Questions

Beginner LevelPython

1. What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

❓ Context: Explain what the GIL is in CPython, why it prevents true parallel execution of CPU-bound threads, and how multiprocessing solves it.

The Global Interpreter Lock (GIL) is a mutex (mutual exclusion lock) used by CPython (the standard Python implementation) that allows only one thread to execute Python bytecode at a time, even on multi-core processors.

Why does the GIL exist?

CPython's memory management uses reference counting. When an object's reference count drops to zero, it is garbage collected. If multiple threads simultaneously increment or decrement reference counts without locking, memory corruption and race conditions occur. The GIL was the simplest, fastest solution to make CPython thread-safe.

Impact on Multi-Threading:

•
CPU-Bound Tasks (Math, Image Processing): Multi-threading in Python does NOT speed up CPU-bound tasks! Because of the GIL, threads take turns executing on a single core, actually running slower due to context switching overhead.
•
I/O-Bound Tasks (Network Requests, File I/O, Database Queries): Multi-threading does work for I/O-bound tasks! When a thread waits for network data or disk I/O, it releases the GIL, allowing other Python threads to run concurrently.

How to Achieve True Parallelism:

To utilize multiple CPU cores for heavy calculations, use the 'multiprocessing' module (which spawns separate OS processes, each with its own memory space and GIL) or Python 3.13+ Free-Threading / GIL-less mode ('--disable-gil').

python
import time
from threading import Thread
from multiprocessing import Process

def heavy_countdown(n):
    while n > 0:
        n -= 1

# 1. Multi-Threading (2 Threads running on 1 Core due to GIL!)
start = time.time()
t1 = Thread(target=heavy_countdown, args=(50_000_000,))
t2 = Thread(target=heavy_countdown, args=(50_000_000,))
t1.start(); t2.start()
t1.join(); t2.join()
print('Threading Time:', round(time.time() - start, 2), 'sec')

# 2. Multiprocessing (2 Processes running in parallel on 2 CPU cores!)
start = time.time()
p1 = Process(target=heavy_countdown, args=(50_000_000,))
p2 = Process(target=heavy_countdown, args=(50_000_000,))
p1.start(); p2.start()
p1.join(); p2.join()
print('Multiprocessing Time:', round(time.time() - start, 2), 'sec')
💡Benchmarking CPU-bound execution times across Threading and Multiprocessing.
🎯 Interview Key Takeaway

The GIL limits Python threads to 1 CPU core. Use threading for I/O-bound tasks and multiprocessing for CPU-bound tasks.

#GIL#Threading#Multiprocessing#Beginner
Permalink
Beginner LevelPython

2. What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

3. Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?

Beginner LevelPython

4. What is the difference between a List Comprehension and a Generator Expression in Python?

Beginner LevelPython

5. How do *args and **kwargs work in Python function definitions?

Beginner LevelPython

6. What is the difference between the `is` operator and the `==` operator in Python?

Beginner LevelPython

7. What is the difference between a Shallow Copy and a Deep Copy in Python?

Beginner LevelPython

8. How does the try-except-else-finally exception handling block execute in Python?

Beginner LevelPython

9. What are Lambda functions and how do you use them with map(), filter(), and sorted()?

Beginner LevelPython

10. What is a Python Decorator and how does the @decorator syntax work?

Beginner LevelPython

11. What is a Generator function and how does the `yield` keyword work?

Beginner LevelPython

12. What are Dunder (Double Underscore) methods in Python and how do they enable operator overloading?

Beginner LevelPython

13. How does the `with` statement manage resources using Context Managers?

Beginner LevelPython

14. Why are Virtual Environments (venv) essential in Python project isolation?

Beginner LevelPython

15. How does Type Hinting in Python (PEP 484) improve code quality and IDE static analysis?

Beginner LevelPython

16. How does the Walrus Operator (:=) work in Python 3.8+?

Beginner LevelPython

17. How do enumerate() and zip() simplify loop iterations in Python?

Beginner LevelPython

18. How do any() and all() evaluate booleans across iterables with short-circuiting?

Beginner LevelPython

19. How do you create custom Exception classes in Python?

Beginner LevelPython

20. Why are f-strings (formatted string literals) superior to % formatting and str.format()?

Beginner LevelPython

21. What is collections.namedtuple and how does it compare to modern @dataclass definitions?

Beginner LevelPython

22. How do dict.get(), dict.setdefault(), and collections.defaultdict prevent KeyError exceptions during lookups?

Beginner LevelPython

23. How does collections.Counter simplify frequency counting and element tallying in sequences?

Beginner LevelPython

24. What are the most useful itertools functions (chain, islice, product, combinations, count)?

Beginner LevelPython

25. How does extended iterable unpacking (first, *middle, last = items) work in assignment statements?

Beginner LevelPython

26. What is the LEGB scope resolution rule (Local, Enclosing, Global, Built-in) and when do you use global vs nonlocal?

Beginner LevelPython

27. Why is "".join(list_of_strings) significantly faster than string concatenation via += in loops?

Beginner LevelPython

28. Which built-in Python objects evaluate to False in boolean contexts (Falsy values)?

Beginner LevelPython

29. What is the difference between pass and Ellipsis (...) as code placeholders or stub bodies?

Beginner LevelPython

30. How do you use pyenv to install and switch between multiple Python runtime versions on the same OS?

Intermediate LevelPython

31. How do you use @dataclass with __post_init__, field(default_factory=...), and frozen=True for immutable domain models?

Intermediate LevelPython

32. How do you create custom Context Managers using __enter__ / __exit__ classes or @contextlib.contextmanager?

Intermediate LevelPython

33. How does Pydantic v2 leverage Rust (pydantic-core) for ultra-fast data validation and settings management?

Intermediate LevelPython

34. What is the difference between __str__() and __repr__() dunder methods for object string representation?

Intermediate LevelPython

35. Why must you implement __hash__() whenever you implement custom __eq__() for objects stored in Sets or Dict keys?

Intermediate LevelPython

36. How does Python resolve method calls in multiple inheritance using the Method Resolution Order (MRO) and C3 Linearization?

Intermediate LevelPython

37. How does super() work in single and multiple inheritance hierarchies and why avoid calling Parent.__init__(self)?

Intermediate LevelPython

38. How does @functools.lru_cache(maxsize=128) optimize recursive functions via Least Recently Used memoization?

Intermediate LevelPython

39. How does functools.partial() fix arguments of existing functions to create new specialized functions (Currying)?

Intermediate LevelPython

40. How do you implement getter, setter, and deleter encapsulation in classes using @property decorators?

Intermediate LevelPython

41. What is the difference between @classmethod (receiving cls) and @staticmethod in Python classes?

Intermediate LevelPython

42. How do you enforce interface contracts on child classes using the abc module and @abstractmethod?

Intermediate LevelPython

43. How does defining __slots__ = ("name", "age") reduce RAM consumption by suppressing per-instance __dict__ creation?

Intermediate LevelPython

44. How do you configure standard library logging with formatters, handlers, and hierarchical logger names instead of print()?

Intermediate LevelPython

45. Why has pytest replaced standard unittest in modern engineering and how do modular pytest fixtures (@pytest.fixture) work?

Intermediate LevelPython

46. How do you mock external API requests and database calls in tests using unittest.mock.patch and MagicMock?

Intermediate LevelPython

47. How do you optimize regular expression matching using re.compile() and raw strings (r"\d+") in the re module?

Intermediate LevelPython

48. Why is pathlib.Path superior to legacy os.path and glob for object-oriented filesystem manipulation?

Intermediate LevelPython

49. How do you execute external shell commands securely and capture stdout/stderr using subprocess.run()?

Intermediate LevelPython

50. How do you serialize custom classes, datetime objects, and UUIDs to JSON by subclassing json.JSONEncoder?

Intermediate LevelPython

51. How do you distribute CPU-bound calculations across multiple CPU cores using multiprocessing.Pool.starmap() or ProcessPoolExecutor?

Intermediate LevelPython

52. How do you prevent thread race conditions on shared memory using threading.Lock, RLock, and Semaphore?

Intermediate LevelPython

53. How does concurrent.futures.ThreadPoolExecutor simplify managing thread pools for concurrent I/O scraping tasks?

Intermediate LevelPython

54. How do you inspect Python runtime internals, command-line arguments (sys.argv), and path entries using the sys module?

Intermediate LevelPython

55. How do you inspect live object signatures, source code, and caller stack frames using the inspect module?

Intermediate LevelPython

56. How do advanced typing constructs (Union, Optional, Literal, Annotated, TypeGuard) enhance static code analysis?

Intermediate LevelPython

57. How do you create type-safe enumerated constants using Enum, IntEnum, and @unique in Python?

Intermediate LevelPython

58. How do you dynamically load and reload Python modules at runtime using importlib.import_module() and reload()?

Intermediate LevelPython

59. How do you build thread-safe Producer-Consumer pipelines using queue.Queue, LifoQueue, and PriorityQueue?

Intermediate LevelPython

60. Why is the pickle module vulnerable to Remote Code Execution (RCE) and when is it acceptable to use?

Intermediate LevelPython

61. How do you pack and unpack C-style binary data structures and network packets using the struct module?

Intermediate LevelPython

62. How does the weakref module allow referencing heavy objects without incrementing their reference count?

Intermediate LevelPython

63. How do you disassemble Python functions into CPython bytecode instructions (LOAD_FAST, BINARY_OP) using the dis module?

Intermediate LevelPython

64. How does contextvars.ContextVar provide thread-local storage equivalents for tracking request IDs across asyncio coroutines?

Intermediate LevelPython

65. Why is dynamic code execution via eval() and exec() dangerous and how do you parse expressions safely with ast.literal_eval()?

Intermediate LevelPython

66. How do you profile deterministic execution bottlenecks in Python scripts using cProfile and SnakeViz?

Intermediate LevelPython

67. How does Structural Pattern Matching (match / case) in Python 3.10+ destructure complex dictionaries and objects?

Intermediate LevelPython

68. Why does itertools.groupby() require sorting input data prior to grouping?

Intermediate LevelPython

69. How does @functools.singledispatch enable Function Overloading based on the type of the first argument?

Intermediate LevelPython

70. How does the strict=True parameter in zip() prevent silent data loss when combining iterables of unequal length?

Senior LevelPython

71. How does Python 3.13+ PEP 703 Free-Threading (No-GIL mode) work and how does it replace reference counting with biased reference counting?

Senior LevelPython

72. How does uvloop replace the default asyncio event loop with Cython libuv bindings to achieve 2x-4x Node.js/Go networking speeds?

Senior LevelPython

73. How do you diagnose and track production memory leaks in CPython using tracemalloc and objgraph?

Senior LevelPython

74. How does the CPython virtual machine bytecode evaluation loop (_PyEval_EvalFrameDefault) execute Code Objects and Stack Frames?

Senior LevelPython

75. How do you write custom AST transformers by subclassing ast.NodeTransformer to rewrite Python source code programmatically before compilation?

Senior LevelPython

76. How do Python 3.12+ Per-Interpreter GILs (PEP 684) enable true multi-core parallelism within a single OS process?

Senior LevelPython

77. How has modern Python dependency management transitioned from setup.py and requirements.txt to pyproject.toml (PEP 517/518) and Rust-powered uv?

Senior LevelPython

78. How do you build memory-safe, ultra-fast Python native extension modules in Rust using PyO3 and compile them with Maturin?

Senior LevelPython

79. How does the ASGI (Asynchronous Server Gateway Interface) specification differ from legacy WSGI, and how does FastAPI/Starlette process asynchronous requests?

Senior LevelPython

80. How does SQLAlchemy architecture implement the Identity Map pattern, Unit of Work, and Lazy Loading descriptors?

Senior LevelPython

81. How do you achieve Zero-Copy inter-process communication for massive NumPy arrays across Python processes using multiprocessing.shared_memory?

Senior LevelPython

82. Why is yaml.load() in PyYAML vulnerable to arbitrary code execution, and why must you strictly enforce yaml.safe_load()?

Senior LevelPython

83. How do you prevent asyncio Event Loop deadlocks caused by running synchronous database drivers (psycopg2) inside async endpoints?

Senior LevelPython

84. How does the Python 3.11+ Specializing Adaptive Interpreter (PEP 659) achieve 25%-50% speedups via inline bytecode caching and type specialization?

Senior LevelPython

85. How do you implement custom import hooks by appending custom MetaPathFinder and Loader objects to sys.meta_path?

Senior LevelPython

86. How do you tune Generational Garbage Collection thresholds (gc.set_threshold(700, 10, 10)) to eliminate GC pause latency spikes in high-throughput API servers?

Senior LevelPython

87. How do you architect resilient distributed task queues in Python using Celery with RabbitMQ brokers, Redis result backends, and acknowledgment worker patterns?

Senior LevelPython

88. How does runtime type checking with Beartype achieve $O(1)$ constant-time validation compared to traditional Pydantic or typeguard approaches?

Senior LevelPython

89. How do you profile production Python container CPU freezes and kernel system call locking using py-spy and strace without restarting processes?

Senior LevelPython

90. How do you dynamically generate ORM models or API serializers at runtime using the 3-argument type(name, bases, dict) constructor?

Senior LevelPython

91. How do you configure strict SSL/TLS verification in Python scripts using ssl.create_default_context() and Mozilla CA bundles via certifi?

Senior LevelPython

92. How does NumPy vectorization bypass loops and utilize CPU SIMD (Single Instruction, Multiple Data) registers via broadcasting?

Senior LevelPython

93. How do you architect decoupled Event-Driven Domain-Driven Design (DDD) systems in Python using internal Pub/Sub Event Buses?

Senior LevelPython

94. In CPython C extensions, what causes fatal segmentation faults or memory leaks when handling Py_INCREF and Py_DECREF ownership rules?

Senior LevelPython

95. How do you architect ultra-lean 60MB production Docker images for Python using multi-stage builds, virtualenvs, and Astral uv?

Senior LevelPython

96. What is the future trajectory of Python (Python 3.13+ GIL removal, copy-and-patch JIT compilation, and type system convergence)?

Senior LevelPython

97. How does asyncio.TaskGroup (Python 3.11+) implement Structured Concurrency to eliminate leaked background tasks?

Senior LevelPython

98. How do ExceptionGroups and except* (PEP 654) handle multiple concurrent exceptions in Python 3.11+?

Senior LevelPython

99. How does CPython's Compact Dictionary layout (PEP 468/509) reduce RAM usage and preserve insertion order?

Senior LevelPython

100. What is the future trajectory of Python (Python 3.13+ GIL removal, copy-and-patch JIT compilation, and type system convergence)?

How to Prepare for Python Technical Interviews in 2026

When interviewing for software engineering positions that utilize Python, hiring managers look for a combination of fundamental syntax proficiency, architectural understanding, code optimization techniques, and practical debugging skills.

🌱 Beginner FocusCore syntax, default configurations, standard API definitions, and avoiding common basic errors.
⚡ Intermediate FocusAsync execution patterns, performance profiling, component lifecycle, and state management.
🏆 Senior FocusInternal runtime mechanics, memory leaks, scalability bottlenecks, system design trade-offs, and security mitigation.