Here's a comprehensive list of Python interview questions categorized by difficulty level, along with sample answers and explanations:
🔰 Beginner-Level Python Questions
1. What is Python? List its key features.
✅ Answer:
Python is an interpreted, high-level, general-purpose programming language. Key features:
Easy-to-read syntax
Dynamically typed
Supports OOP, functional & procedural programming
Extensive standard library
Cross-platform compatibility
2. Explain Python's GIL (Global Interpreter Lock).
✅ Answer:
The GIL is a mutex that allows only one thread to execute Python bytecode at a time, limiting multi-threading performance but simplifying memory management.
3. Difference between list and tuple?
✅ Answer:
| List | Tuple |
|---|---|
| Mutable | Immutable |
Uses [] | Uses () |
| Slower | Faster |
4. How does Python manage memory?
✅ Answer:
Uses private heap space for objects
Reference counting (objects deleted when count=0)
Garbage collector removes cyclic references
5. Write code to reverse a string.
s = "hello" print(s[::-1]) # Output: "olleh"
📊 Intermediate-Level Questions
6. Explain *args and **kwargs.
✅ Answer:
*args: Accepts variable positional arguments (stored as tuple)**kwargs: Accepts variable keyword arguments (stored as dict)
7. What are decorators? Show an example.
✅ Answer:
Decorators modify/extend function behavior without changing its code.
def log_time(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"Time taken: {time.time() - start}") return result return wrapper @log_time def calculate(): time.sleep(2)
8. Difference between deepcopy and shallow copy?
✅ Answer:
Shallow copy: Copies references (changes affect original)
Deep copy: Creates new objects (independent of original)
9. How to handle exceptions in Python?
✅ Answer:
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Cleanup code")
10. Explain Python's __init__ and __new__.
✅ Answer:
__new__: Creates the instance (called first)__init__: Initializes the instance (called after__new__)
🚀 Advanced-Level Questions
11. What are metaclasses in Python?
✅ Answer:
Metaclasses are classes of classes that control class creation. Example:
class Meta(type): def __new__(cls, name, bases, dct): dct['version'] = 1.0 return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass print(MyClass.version) # Output: 1.0
12. How does Python's garbage collector work?
✅ Answer:
Uses generational garbage collection (0=young, 1=older, 2=oldest)
Cycle detector removes unreachable reference cycles
13. Optimize this code for large datasets:
result = [x**2 for x in range(10_000_000)]
✅ Optimized Answer:
Use a generator to save memory:
result = (x**2 for x in range(10_000_000))
14. Explain Python's asyncio with an example.
✅ Answer:asyncio enables single-threaded concurrent code using coroutines.
import asyncio async def fetch_data(): await asyncio.sleep(2) return "Data" async def main(): task = asyncio.create_task(fetch_data()) await task print(task.result()) asyncio.run(main())
15. How to make Python code thread-safe?
✅ Answer:
Use
threading.Lock:
import threading lock = threading.Lock() def safe_increment(): with lock: global counter counter += 1
🧠Scenario-Based Questions
16. How would you debug a memory leak?
✅ Approach:
Use
tracemallocto track allocationsProfile with
memory_profilerCheck for cyclic references
17. Design a LRU Cache in Python.
✅ Solution:
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.cache = OrderedDict() self.capacity = capacity def get(self, key): if key not in self.cache: return -1 self.cache.move_to_end(key) return self.cache[key] def put(self, key, value): if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False)
18. How would you deploy a Python ML model?
✅ Steps:
Serialize model (
pickle/joblib)Create Flask/FastAPI endpoint
Containerize with Docker
Deploy on AWS/GCP
📌 Bonus: Top 5 Python Libraries to Know
NumPy (Scientific computing)
Pandas (Data analysis)
Django/Flask (Web frameworks)
PyTorch/TensorFlow (ML/DL)
Asyncio (Concurrency)
No comments:
Post a Comment