Wednesday, April 30, 2025

Python interview questions

 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:

ListTuple
MutableImmutable
Uses []Uses ()
SlowerFaster

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.

python
Copy
Download
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.

python
Copy
Download
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:

python
Copy
Download
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:

python
Copy
Download
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:

python
Copy
Download
result = [x**2 for x in range(10_000_000)]

✅ Optimized Answer:
Use a generator to save memory:

python
Copy
Download
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.

python
Copy
Download
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:

python
Copy
Download
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:

  1. Use tracemalloc to track allocations

  2. Profile with memory_profiler

  3. Check for cyclic references

17. Design a LRU Cache in Python.
✅ Solution:

python
Copy
Download
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:

  1. Serialize model (pickle/joblib)

  2. Create Flask/FastAPI endpoint

  3. Containerize with Docker

  4. Deploy on AWS/GCP


📌 Bonus: Top 5 Python Libraries to Know

  1. NumPy (Scientific computing)

  2. Pandas (Data analysis)

  3. Django/Flask (Web frameworks)

  4. PyTorch/TensorFlow (ML/DL)

  5. Asyncio (Concurrency)



No comments:

Post a Comment