Python Notes
Top 25+ Python interview questions and detailed answers covering Python basics, OOP, data structures, exceptions, and advanced topics with Hindi explanations for job interviews.
Introduction
Yeh guide top Python interview questions aur unke detailed answers cover karta hai. Yeh questions freshers se leke experienced developers tak sabke liye useful hain.
Q2: Mutable aur Immutable objects ka difference kya hai?
Answer:
- Mutable: Created ke baad change ho sakta hai (list, dict, set)
- Immutable: Created ke baad change NAHI ho sakta (int, float, str, tuple, frozenset)
Q3: *args aur **kwargs kya hain?
Answer: *args arbitrary positional arguments tuple mein collect karta hai. **kwargs arbitrary keyword arguments dictionary mein collect karta hai.
Q4: Python mein list, tuple, set aur dict ka difference kya hai?
Answer:
| Feature | List | Tuple | Set | Dict |
|---|---|---|---|---|
| Mutable | ✅ | ❌ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ✅(3.7+) |
| Duplicates | ✅ | ✅ | ❌ | Keys: ❌ |
| Syntax | [] | () | {} | {k:v} |
| Indexing | ✅ | ✅ | ❌ | By key |
Q5: Lambda functions kya hain?
Answer: Lambda ek anonymous function hai — ek single line mein define hota hai, bina def keyword ke.
Q6: List Comprehension kya hai? Generator Expression se kya fark hai?
Q7: Python mein Exception Handling kaise karte hain?
Q8: Python mein decorators kya hain?
import functools
import time
# Simple decorator
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timer
def slow_function(n):
return sum(range(n))
result = slow_function(1000000)
# Output: slow_function took 0.0234s
# Decorator with arguments
def retry(max_attempts=3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
print(f"Attempt {attempt+1} failed: {e}")
return wrapper
return decorator
import random
@retry(max_attempts=3)
def unreliable():
if random.random() < 0.7:
raise ValueError("Failed!")
return "Success!"
# try:
# print(unreliable())
# except ValueError:
# print("All retries failed")Q9: Python mein shallow copy aur deep copy kya hai?
Q10: Python mein is aur == ka difference kya hai?
Q11: Python mein GIL kya hai?
"""
GIL (Global Interpreter Lock):
- CPython interpreter mein ek mutex lock hai
- Ek waqt mein sirf ek thread Python bytecode execute kar sakta hai
- Thread safety ke liye exist karta hai (Python objects ko protect karta hai)
- CPU-bound tasks: threading se speedup NAHI (GIL blocks)
- I/O-bound tasks: threading se speedup milta hai (I/O ke dauran GIL release)
Solutions:
- CPU-bound: use multiprocessing (separate GIL per process)
- I/O-bound: use threading or asyncio
"""
import threading
import time
# GIL effect on CPU-bound
def cpu_work():
total = sum(i * i for i in range(1_000_000))
start = time.time()
cpu_work()
cpu_work()
print(f"Sequential: {time.time() - start:.2f}s")
t1 = threading.Thread(target=cpu_work)
t2 = threading.Thread(target=cpu_work)
start = time.time()
t1.start(); t2.start()
t1.join(); t2.join()
print(f"Threaded: {time.time() - start:.2f}s") # Similar or SLOWER!
# GIL released during I/O
import time
def io_simulation():
time.sleep(1) # GIL released during sleep!
start = time.time()
t1 = threading.Thread(target=io_simulation)
t2 = threading.Thread(target=io_simulation)
t1.start(); t2.start()
t1.join(); t2.join()
print(f"I/O threaded: {time.time() - start:.2f}s") # ~1s, not 2s!Q12: Python mein generators aur iterators kya hain?
Q13: Python mein namespaces aur scope (LEGB) kya hai?
# LEGB Rule: Local > Enclosing > Global > Built-in
x = "Global" # Global scope
def outer():
x = "Enclosing" # Enclosing scope
def inner():
x = "Local" # Local scope
print(f"Inner: {x}") # Local
inner()
print(f"Outer: {x}") # Enclosing
outer()
print(f"Global: {x}") # Global
# global keyword
count = 0
def increment():
global count
count += 1
increment()
increment()
print(f"Count: {count}") # 2
# nonlocal keyword
def make_counter():
n = 0
def counter():
nonlocal n
n += 1
return n
return counter
c = make_counter()
print(c()) # 1
print(c()) # 2
print(c()) # 3Q14: Python mein map(), filter(), reduce() kya hain?
Q15: Python mein class methods, static methods aur instance methods kya hain?
Q16: Python mein __init__ aur __new__ ka difference kya hai?
class MyClass:
def __new__(cls, *args, **kwargs):
print(f"__new__ called — creating instance of {cls}")
instance = super().__new__(cls) # Object create karo
return instance # Must return instance!
def __init__(self, value):
print(f"__init__ called — initializing with value={value}")
self.value = value
obj = MyClass(42)
# Output:
# __new__ called — creating instance of <class '__main__.MyClass'>
# __init__ called — initializing with value=42
print(obj.value) # 42
"""
__new__: Object CREATION — memory allocate karta hai
__init__: Object INITIALIZATION — attributes set karta hai
Mostly __init__ hi use karte hain.
__new__ use karo jab: Singleton pattern, immutable subclassing (int, str)
"""
# Singleton using __new__
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True — same object!Q17: Python mein with statement aur context managers kya hain?
# Without context manager — risky
f = open("test.txt", "w")
f.write("Hello")
f.close() # What if exception occurs before this?
# With context manager — safe
with open("test.txt", "w") as f:
f.write("Hello")
# File automatically closed, even if exception occurs
# Custom context manager
class DatabaseContext:
def __enter__(self):
print("Connecting to database...")
self.connection = "DB Connection"
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
print("Disconnecting from database...")
if exc_type:
print(f"Error occurred: {exc_val}")
return False # Don't suppress exceptions
with DatabaseContext() as db:
print(f"Using: {db}")
# Using contextlib.contextmanager
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"Time taken: {time.time() - start:.4f}s")
with timer():
total = sum(range(1_000_000))Q18: Python mein type hints kya hain?
Q19: Python mein enumerate() aur zip() kya karte hain?
Q20: Python mein any() aur all() kya karte hain?
Q21: Python mein __str__ aur __repr__ ka difference kya hai?
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __str__(self):
"""Human-readable representation (for users)"""
return f"{self.name} — Marks: {self.marks}%"
def __repr__(self):
"""Developer-friendly representation (for debugging)"""
return f"Student(name='{self.name}', marks={self.marks})"
s = Student("Alice", 95)
print(str(s)) # Alice — Marks: 95% (uses __str__)
print(repr(s)) # Student(name='Alice', marks=95) (uses __repr__)
# In f-strings
print(f"{s}") # Alice — Marks: 95% (calls __str__)
print(f"{s!r}") # Student(name='Alice', marks=95) (forces __repr__)
# Rule: __repr__ should ideally be eval()-able
s2 = eval(repr(s)) # Should recreate the object
print(s2.name) # AliceQ22: Python mein walrus operator := kya hai?
Q23: Python mein dataclasses kya hain?
Q24: Python mein slots kya hain?
Q25: Python mein isinstance() aur type() mein kya fark hai?
Quick Summary — Interview Tips
# Key concepts to remember:
# 1. Everything in Python is an object
# 2. Python uses duck typing ("if it quacks like a duck...")
# 3. Mutable default arguments are dangerous
# 4. GIL limits CPU parallelism in threading
# 5. Use isinstance() over type()
# 6. Use functools.wraps() in decorators
# 7. Generators save memory for large sequences
# 8. Context managers ensure cleanup with 'with'
# 9. LEGB rule for scope resolution
# 10. Deep copy vs shallow copy for nested objectsInterview Pro Tip: Practice writing code on paper/whiteboard. Explain your thought process aloud. Ask clarifying questions before coding. Think about edge cases. Talk about time and space complexity.
📤 Output Examples — Code Outputs at a Glance
Yahan kuch important code snippets ke outputs hain jo interviews mein frequently puchhe jaate hain:
<class 'list'>
# Q2: Mutable Default Argument Bug
def bad_func(items=[]):
items.append("new")
return items
print(bad_func())
print(bad_func())
print(bad_func())['new'] ['new', 'new'] ['new', 'new', 'new']
[95, 87, 100]
True False
# Q13: LEGB Scope
x = "Global"
def outer():
x = "Enclosing"
def inner():
x = "Local"
print(f"Inner: {x}")
inner()
print(f"Outer: {x}")
outer()
print(f"Global: {x}")Inner: Local Outer: Enclosing Global: Global
# Q16: __new__ vs __init__
class MyClass:
def __new__(cls, *args, **kwargs):
print("__new__ called")
return super().__new__(cls)
def __init__(self, value):
print(f"__init__ called with {value}")
obj = MyClass(42)__new__ called __init__ called with 42
True False
List has 5 elements
# Q25: isinstance vs type
class Animal: pass
class Dog(Animal): pass
dog = Dog()
print(type(dog) == Animal)
print(isinstance(dog, Animal))False True
⚠️ Common Mistakes
Python interviews mein yeh galtiyan bahut common hain — inse bachna seekho! 🚫
1. Mutable Default Arguments Use Karna ❌
['a'] ['a', 'b']
Hindi: Mutable objects (list, dict, set) ko kabhi function default argument mein mat do. Python function define hone pe ek baar hi default evaluate karta hai — har call pe nahi!
2. is aur == Confuse Karna ❌
# ❌ WRONG
name = "hello"
if name is "hello": # Identity check — unreliable!
print("Match")
# ✅ CORRECT
if name == "hello": # Value check — reliable!
print("Match")Hindi:issirfNone,True,Falseke saath use karo. Baaki sab ke liye==use karo.ismemory address compare karta hai, value nahi!
3. Shallow Copy samajh ke Deep Copy expect karna ❌
[[1, 2, 99], [3, 4]]
Hindi: Jab bhi nested objects (list of lists, dict of dicts) ho, always copy.deepcopy() use karo agar independent copy chahiye.4. Exception mein bare except: use karna ❌
# ❌ WRONG — catches EVERYTHING including KeyboardInterrupt
try:
result = 10 / 0
except:
print("Something went wrong")
# ✅ CORRECT — specific exceptions catch karo
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Math error: {e}")
except Exception as e:
print(f"Unexpected: {e}")Hindi: Bareexcept:kabhi mat likho — yehSystemExitaurKeyboardInterruptbhi catch kar leta hai. Hamesha specific exception name lo.
5. Loop mein list modify karna ❌
[1, 3, 5]
Hindi: Jis list pe iterate kar rahe ho, usiko modify mat karo. List comprehension ya copy pe iterate karo.
6. Global variables overuse karna ❌
# ❌ WRONG — sab kuch global
count = 0
def increment():
global count
count += 1
# ✅ CORRECT — encapsulation use karo
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 21 2
Hindi: global ka overuse code ko unpredictable banata hai. Closures, classes ya function parameters prefer karo.7. String concatenation loop mein karna ❌
# ❌ SLOW — O(n²) time complexity
result = ""
for i in range(10000):
result += str(i) # Har iteration mein new string banati hai!
# ✅ FAST — O(n) time complexity
result = "".join(str(i) for i in range(10000))Hindi: Strings immutable hain —+=har baar new string create karta hai. Large data ke liye"".join()use karo — 10x faster hai!
✅ Key Takeaways
Interview mein yeh points yaad rakho — yeh foundation hai Python mastery ka! 💡
- 🐍 Everything is an Object — Python mein integers, functions, classes sab objects hain.
id(),type()se verify karo.
- 🔒 Mutable vs Immutable samjho — Yeh concept interviews ka bread and butter hai. Lists mutable hain, tuples/strings immutable. Default arguments mein mutable objects = bug!
- 🧠 GIL ka impact jaano — CPU-bound tasks ke liye
multiprocessinguse karo, I/O-bound ke liyethreadingyaasyncio. GIL sirf CPython mein hai.
- 🎯 LEGB Rule yaad rakho — Variable lookup order: Local → Enclosing → Global → Built-in.
globalaurnonlocalkeywords kab use karne hain, yeh clear hona chahiye.
- 📦 Generators memory bachate hain — Large datasets ke liye generators (
yield) use karo, puri list memory mein load mat karo. Lazy evaluation = efficient!
- 🛡️ Context Managers (
with) cleanup ensure karte hain — File handling, DB connections, locks — hameshawithstatement use karo. Resource leaks se bachao!
- 🎨 Decorators samjho aur likho —
@functools.wrapshamesha use karo. Decorator = function jo function ko modify kare bina original code change kiye.
- 📐 Type Hints code quality badhate hain — Runtime pe enforce nahi hote, but IDE support aur
mypyse bugs pakad sakte ho before deployment.
- 🔄 Deep Copy vs Shallow Copy — Nested objects ke saath kaam karte waqt always
copy.deepcopy()consider karo. Interview mein yeh tricky question bahut aata hai.
- 🏗️ OOP concepts clear rakho —
__init__vs__new__,@classmethodvs@staticmethod,__str__vs__repr__— yeh basics interviews mein 100% puchhe jaate hain.
❓ FAQ
Python interview preparation ke liye kitna time chahiye?
Agar aapko Python basics aate hain, toh 2-3 weeks ka focused preparation kaafi hai. Daily 2-3 questions practice karo with code. Agar beginner ho toh 1-2 months plan karo. Concepts + coding dono parallel chale! 📅
Kya Python interviews mein DSA bhi puchha jaata hai?
Haan, bilkul! 🎯 Especially product-based companies (Google, Amazon, Microsoft) mein Data Structures + Algorithms Python mein solve karne hote hain. Arrays, linked lists, trees, graphs, dynamic programming — sab cover karo. Python-specific DSA (deque, heapq, bisect) bhi jaano.
Freshers ke liye sabse important Python topics kaun se hain?
Freshers ke liye yeh topics must-know hain: (1) Data types & mutability, (2) List/Dict comprehensions, (3) Functions — *args, **kwargs, lambda, (4) OOP basics — inheritance, polymorphism, (5) Exception handling, (6) File I/O, (7) Basic modules — os, sys, json. Yeh 7 topics cover karo, interview mein 80% questions in se aayenge! 📚
Python 2 vs Python 3 — interview mein kya puchha jaata hai?
Ab zyada companies Python 3 pe focus karti hain. Main differences yaad rakho: print() function vs statement, integer division (/ vs //), range() vs xrange(), Unicode strings default in Python 3, input() behavior. But Python 2 ko deeply padhne ki zaroorat nahi — just key differences jaano. 🔄
Remote Python interviews mein kya different hota hai?
Remote interviews mein usually ek online coding platform milta hai (HackerRank, CodeSignal, CoderPad). Tips: (1) Apna mic/camera check karo, (2) Screen sharing smooth honi chahiye, (3) Code likhte waqt think aloud — apni thought process explain karo, (4) Edge cases pehle discuss karo, (5) IDE shortcuts yaad rakho. Practice karo online editors mein coding! 💻
Python mein design patterns puchhe jaate hain kya?
Senior/mid-level roles mein haan! Common patterns: Singleton (__new__), Factory, Observer, Decorator (already Python mein built-in), Iterator (__iter__/__next__), Context Manager (__enter__/__exit__). Freshers ke liye basic Singleton aur Factory enough hai. 🏛️
Interview mein code run nahi ho raha — kya karu?
Don't panic! 😅 (1) Pehle logic explain karo interviewer ko, (2) Dry run karo mentally with a small example, (3) Edge cases check karo — empty input, None, negative numbers, (4) Syntax errors dhundo — indentation, colons, parentheses. Interviewer approach dekhta hai, perfect code zaroori nahi!
Kya frameworks (Django/Flask) ke questions bhi aate hain?
Yeh role pe depend karta hai. Backend Developer role mein Django/Flask zaroor puchha jaata hai. But pure Python Developer role mein core Python + OOP + DSA focus hota hai. Job description carefully padho — usme clearly likha hota hai kya expect hai. Both scenarios ke liye core Python strong hona mandatory hai! 🎪
🎯 Interview Tips
Python interview crack karne ke liye yeh actionable tips follow karo! 🚀
1. 📝 Pehle Approach Explain Karo, Phir Code Likho
Interviewer ko seedha code mat dikhao. Pehle bolo: "Main yeh approach use karunga because..." — isse interviewer ko lagta hai ki aap think kar rahe ho, blindly code nahi likh rahe.
2. 🧪 Edge Cases Pehle Identify Karo
Code likhne se pehle bolo: "Edge cases honge — empty list, None input, negative numbers, duplicate values." Yeh interviewer ko impress karta hai because most candidates yeh skip kar dete hain.
3. ⏱️ Time & Space Complexity Batao
Har solution ke baad bolo: "Yeh O(n) time aur O(1) space hai." Agar interviewer nahi puchhe tab bhi voluntarily batao — yeh shows depth of understanding.
4. 🐍 Pythonic Code Likho
Interviewer Pythonic code dekhna chahta hai — list comprehensions, f-strings, enumerate(), zip() use karo!
5. 🗣️ Think Aloud — Chup Mat Raho
Silence = red flag in interviews. Sochte waqt bhi bolo: "Main soch raha hoon ki yahan dictionary use karun ya set..." — yeh communication skills demonstrate karta hai.
6. 🔄 Brute Force Pehle, Optimize Baad Mein
First working solution do (even if O(n²)), phir bolo: "Ab isko optimize karta hoon O(n) mein." Yeh shows iterative thinking — interviewers love this approach!
7. 📚 Standard Library Jaano
collections (Counter, defaultdict, deque), itertools (combinations, permutations), functools (lru_cache, reduce) — yeh modules interview mein bahut kaam aate hain. Inke 2-3 use cases yaad rakho.
8. ❓ Clarifying Questions Puchho
Question sunke seedha code mat likho! Puchho: "Input ka type kya hoga? Negative numbers aa sakte hain? Output sorted chahiye? Duplicates handle karne hain?" — yeh senior-level thinking dikhata hai.
9. 🧩 Real Projects ka Reference Do
Jab bhi concept explain karo, real example do: "Maine apne project mein decorators use kiye the for caching API responses" — yeh shows practical experience, not just textbook knowledge.
10. 🎯 Mock Interviews Practice Karo
Friends ke saath ya platforms (Pramp, Interviewing.io) pe weekly mock interviews do. Camera on karke practice karo — real interview jaise environment create karo. Practice mein nervous feel ho, toh real mein confident lagoge! 💪
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Interview Questions and Answers.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, interview, preparation, questions
Related Python Master Course Topics