Top Python Interview Questions and Answers
Top Python Interview Questions and Answers
Python remains one of the most in-demand languages thanks to its simplicity, extensive ecosystem, and versatility across web development, data science, AI/ML, scripting, and DevOps. This guide compiles the top 100 questions—organized into Basic, Intermediate, Advanced, and Coding—so you can revise quickly and answer confidently. Each question includes a concise sample answer you can expand during prep.
Related guides: Python Cheat Sheet • Python Data Structures • OOP in Python
Basic Python Interview Questions
-
What are Python's key features?
Sample answer: Interpreted, dynamically typed, high-level; large standard library; multi-paradigm; cross-platform.
-
List vs tuple vs set vs dict?
- List: ordered, mutable, duplicates allowed
- Tuple: ordered, immutable
- Set: unordered, unique items
- Dict: key-value mapping (insertion-ordered in 3.7+)
my_list=[1,2,3]; my_tuple=(1,2,3); my_set={1,2,3}; my_dict={"a":1} -
What is list comprehension?
squares=[x*x for x in range(10) if x%2==0] -
How does slicing work?
s="interview"\nprint(s[:5])\nprint(s[-3:])\nprint(s[::-1]) -
== vs is?
Sample answer: == compares values; is compares object identity.
-
Exceptions—basic pattern?
try:\n risky()\nexcept ValueError as e:\n print(e)\nfinally:\n cleanup() -
Virtual environments?
python -m venv .venv\nsource .venv/bin/activate # Windows: .venv\\Scripts\\activate -
Module vs package?
Sample answer: Module=.py file; Package=folder of modules, often with __init__.py.
-
Mutable vs immutable?
Sample answer: Mutable (list/dict/set) can change in place; immutable (int/str/tuple) cannot.
-
Useful built-ins?
list(map(str,[1,2]))\nlist(filter(lambda x:x%2==0, range(6)))\nlist(zip('ab',[1,2]))\nlist(enumerate(['x','y']))
Intermediate Python Interview Questions
-
Iterables vs iterators vs generators?
Sample answer: Iterable → iterator; iterator has __iter__/__next__; generators are lazy iterators via yield.
def gen(n):\n for i in range(n):\n yield i*i -
What is the GIL?
Sample answer: A CPython lock allowing one thread to run Python bytecode at a time; use multiprocessing for CPU-bound, threading/asyncio for I/O-bound.
-
Shallow vs deep copy?
import copy\nshallow=copy.copy(obj)\ndeep=copy.deepcopy(obj) -
Decorators—why?
from functools import wraps\ndef log(fn):\n @wraps(fn)\n def wrapper(*a,**k):\n print(fn.__name__)\n return fn(*a,**k)\n return wrapper -
Context managers?
with open('f.txt') as f:\n data=f.read() -
Dataclasses vs namedtuple?
Sample answer: Dataclass: class-like with generated methods; namedtuple: lightweight immutable tuple-like.
-
Type hints?
Sample answer: Improve tooling and clarity; checked by mypy/pyright.
-
List vs generator expressions?
Sample answer: Lists allocate; generators are lazy and memory-efficient.
-
*args and **kwargs?
Sample answer: Collect variable positional and keyword arguments.
-
Error handling best practices?
- Catch specific exceptions
- Avoid bare except
- Use finally for cleanup and logging
Advanced Python Interview Questions
-
Descriptors?
Sample answer: Objects implementing __get__/__set__/__delete__ to control attribute access; used by property.
-
Metaclasses?
Sample answer: Classes that create classes; customize class creation via metaclass __new__/__init__.
-
Asyncio essentials?
import asyncio\nasync def fetch(x):\n await asyncio.sleep(1); return x\nasync def main():\n r=await asyncio.gather(*(fetch(i) for i in range(3))); print(r) -
Memory management?
Sample answer: Reference counting + cyclic GC; weakref for avoiding cycles.
-
Performance tuning?
- Prefer built-ins and C-optimized libs (itertools, numpy)
- Profile (cProfile), measure (timeit)
- Use lru_cache for pure functions
-
Multiprocessing vs threading?
Sample answer: CPU-bound → multiprocessing; I/O-bound → threading/asyncio; consider IPC overhead.
-
Packaging and distribution?
Sample answer: Use pyproject.toml; build wheels; upload with twine to PyPI.
-
property vs cached_property?
Sample answer: property computes per access; cached_property computes once per instance.
-
contextvars?
Sample answer: Context-local state for async code propagating across task switches.
-
Advanced typing?
Sample answer: Protocols, TypedDict, Literal, Final, Annotated, ParamSpec, TypeVar.
Coding Questions (with Solutions)
Below are representative coding challenges with concise solutions. Adapt them to your preferred patterns.
| # | Problem | Approach | Code |
|---|---|---|---|
| 1 | Reverse a string | Slicing |
def rev(s: str) -> str:\n return s[::-1]
|
| 2 | Check palindrome | Normalize + compare |
def is_pal(s: str) -> bool:\n t=''.join(ch.lower() for ch in s if
ch.isalnum())\n return t==t[::-1]
|
| 3 | Two-sum indices | Hash map |
def two_sum(a, target):\n seen={}\n for i,x in enumerate(a):\n if
target-x in seen: return [seen[target-x], i]\n seen[x]=i
|
| 4 | Fibonacci (iterative) | Loop |
def fib(n):\n a,b=0,1\n for _ in range(n): a,b=b,a+b\n return a
|
| 5 | Anagram check | Counter |
from collections import Counter\ndef is_anagram(a,b):\n return
Counter(a.replace(' ','').lower())==Counter(b.replace('
','').lower())
|
Frequently Asked Questions
- Is Python still in demand?
- Yes—Python remains a top choice for data, AI/ML, web, and automation roles.
- How should I practice for interviews?
- Review fundamentals, implement data structures/algorithms, and solve 20–40 coding problems.
- Which version should I install?
- Use the latest stable Python 3.x; many libraries support 3.9+ and newer.
- Do I need frameworks?
- Know basics first; then optionally explore Flask/FastAPI for web and pandas/NumPy for data.
Conclusion
With these questions and examples, you can efficiently revise Python fundamentals and advanced topics while practicing practical coding tasks. Bookmark this page, explore the related internal links, and iterate on your answers to build confidence for your next interview.