Advanced Python Interview Questions
π Crack the Code: Advanced Python Interview Questions (With Deep Explanations & Examples) ππ₯
Python interviews at a senior / advanced level donβt test syntaxβthey test how you think. This guide will help you stand out by mastering advanced concepts, real-world examples, and interview-winning tricks π‘
π§ 1. What is the difference between __new__() and __init__()?
π Explanation
__new__()creates the object__init__()initializes the object
__new__() is called before __init__().
π§ͺ Example
class Demo:
def __new__(cls):
print("Creating instance")
return super().__new__(cls)
def __init__(self):
print("Initializing instance")
obj = Demo()
β Output
Creating instance
Initializing instance
π Used in: Singletons, immutable objects
π§ 2. Explain Pythonβs Global Interpreter Lock (GIL)
π Explanation
The GIL allows only one thread to execute Python bytecode at a time.
β Problem
- CPU-bound multithreading doesnβt scale well
β Solution
- Use multiprocessing for CPU-bound tasks
- Use async / threading for I/O-bound tasks
π§ͺ Example
import threading
def task():
print("Running task")
threading.Thread(target=task).start()
π§ Interview Tip: π Python threads β true parallelism (for CPU tasks)
π§ 3. What are Python Decorators? How do they work internally?
π Explanation
Decorators wrap functions to modify behavior without changing original code.
π§ͺ Example
def log(func):
def wrapper():
print("Before execution")
func()
print("After execution")
return wrapper
@log
def hello():
print("Hello World")
hello()
β Output
Before execution
Hello World
After execution
π Used in: Authentication, logging, caching, rate-limiting
π§ 4. Explain Mutable vs Immutable Objects
π Explanation
| Mutable | Immutable |
|---|---|
| Can change | Cannot change |
| list, dict, set | int, tuple, str |
π§ͺ Example
a = [1, 2]
b = a
b.append(3)
print(a)
β Output
[1, 2, 3]
β οΈ Common Interview Trap
π§ 5. What is Pythonβs Memory Management?
π Explanation
Python uses:
- Reference Counting
- Garbage Collection (GC) for cyclic references
π§ͺ Example
import sys
x = []
print(sys.getrefcount(x))
π GC handles cycles like:
a = []
b = []
a.append(b)
b.append(a)
π§ 6. What are Metaclasses?
π Explanation
Metaclasses define how classes behave
βClasses are objects too!β
π§ͺ Example
class Meta(type):
def __new__(cls, name, bases, dct):
dct["version"] = 1.0
return super().__new__(cls, name, bases, dct)
class App(metaclass=Meta):
pass
print(App.version)
π Used in: ORMs, frameworks like Django
π§ 7. What is Monkey Patching?
π Explanation
Changing a class or module at runtime
π§ͺ Example
class A:
def greet(self):
return "Hello"
def new_greet(self):
return "Hi"
A.greet = new_greet
print(A().greet())
β οΈ Avoid in production unless absolutely required
π§ 8. Explain *args and **kwargs in Depth
π Explanation
*argsβ Variable positional arguments**kwargsβ Variable keyword arguments
π§ͺ Example
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, a=10, b=20)
π Used in: APIs, decorators, extensible functions
π§ 9. What are Generators and Why Are They Memory Efficient?
π Explanation
Generators yield values one at a time, saving memory.
π§ͺ Example
def count_up(n):
for i in range(n):
yield i
gen = count_up(1000000)
π₯ Huge performance boost for large datasets
π§ 10. Difference Between Deep Copy and Shallow Copy
π Explanation
- Shallow Copy β References
- Deep Copy β New objects
π§ͺ Example
import copy
a = [[1, 2]]
b = copy.copy(a)
c = copy.deepcopy(a)
a[0].append(3)
print(b)
print(c)
π§ 11. What is Pythonβs __slots__?
π Explanation
Reduces memory usage by preventing dynamic attribute creation.
π§ͺ Example
class User:
__slots__ = ["name", "age"]
u = User()
u.name = "Alex"
π Used in: Performance-critical systems
π§ 12. Explain Async/Await in Python
π Explanation
Used for non-blocking I/O
π§ͺ Example
import asyncio
async def main():
await asyncio.sleep(1)
print("Done")
asyncio.run(main())
β‘ Faster than threading for I/O tasks
π― Interview Tips & Tricks (Must Read!) π₯
β 1. Think Out Loud
Interviewers care about reasoning, not just answers π§
β 2. Use Real-World Examples
Relate answers to APIs, background jobs, data processing
β 3. Know Trade-offs
Always explain pros vs cons βοΈ
β 4. Master These Topics
- OOP & Design Patterns
- Memory Management
- Concurrency
- Data Structures
- Performance Optimization
β 5. Write Clean Code
Readable > Clever π§Ό
β¨ Final Words
π¬ βPython rewards clarity of thought more than clever tricks.β
Master these advanced Python concepts, and youβll walk into any interview with confidence & clarity ππ
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.