India's Most Trusted Education Portal
Python Interview Questions, Data structures, Decorators, Generators, and OOPs concepts.
@decorator_name above the function.import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Time: {time.time()-start:.4f}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)
slow_func() # Output: Time: 1.0001s yield keyword instead of returning all at once.def count_up(n):
for i in range(n):
yield i
gen = count_up(1000000) # No memory issue!
next(gen) # 0
next(gen) # 1 def greet(*args):
for name in args:
print(f"Hello {name}")
greet("Alice", "Bob", "Charlie")def info(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
info(name="Alice", age=25) [expression for item in iterable if condition]# Squares of 0-9
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Even numbers only
evens = [x for x in range(20) if x%2==0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested — flatten matrix
matrix = [[1,2],[3,4],[5,6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6] copy.copy() or slice [:]copy.deepcopy()import copy
original = [[1,2],[3,4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
# shallow[0][0] = 99 (affected!)
# deep[0][0] = 1 (not affected) multiprocessing module (separate processes)__init__ — Constructor__str__ — String representation (print)__repr__ — Official string representation__len__ — len() function__add__ — + operator__eq__ — == operator__lt__ — < operatorclass Vector:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, other): return Vector(self.x+other.x, self.y+other.y)
def __str__(self): return f"({self.x}, {self.y})" class Math:
@staticmethod
def add(a, b): return a + b
Math.add(2, 3) # 5cls) as first argumentclass Person:
count = 0
@classmethod
def get_count(cls): return cls.count try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("Type or value error")
else:
print("No error occurred") # runs if no exception
finally:
print("Always runs") # cleanup codeclass MyError(Exception):
def __init__(self, msg):
super().__init__(msg)
raise MyError("Something went wrong") lambda keyword.lambda arguments: expression# Regular function
def square(x): return x**2
# Lambda equivalent
square = lambda x: x**2
square(5) # 25
# With map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
# [1, 4, 9, 16]
# With filter()
evens = list(filter(lambda x: x%2==0, nums))
# [2, 4] x = 42
print(type(x)) #
print(isinstance(x, int)) # Truestr(42) # "42"
int("42") # 42
float(42) # 42.0
list((1,2)) # [1, 2] a = [1, 2, 3]
b = [1, 2, 3]
c = a
a == b # True (same values)
a is b # False (different objects)
a is c # True (same object)
# Integer caching (-5 to 256)
x = 256
y = 256
x is y # True (cached)
x = 257
y = 257
x is y # False (not cached) __init__.py file makes a directory a Python package, allowing its modules to be imported.__all__mypackage/
__init__.py # Makes it a package
module1.py
module2.py
# Import
from mypackage import module1
from mypackage.module2 import some_functionimport gc
gc.collect() # manual GC triggerimport sys
print(sys.getsizeof([])) # 56 bytes
print(sys.getsizeof([1,2,3])) # 88 bytes nums = [1,2,3,4]
result = list(map(lambda x: x*2, nums))
# [2, 4, 6, 8]evens = list(filter(lambda x: x%2==0, nums))
# [2, 4]from functools import reduce
total = reduce(lambda x,y: x+y, nums)
# 10 (1+2+3+4) with statement ensures resources are properly acquired and released, even if exceptions occur.# Without with (manual close needed)
f = open("file.txt", "r")
try:
data = f.read()
finally:
f.close()
# With with (automatic close)
with open("file.txt", "r") as f:
data = f.read()
# File auto-closed hereclass Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
print(f"Elapsed: {time.time()-self.start:.2f}s") s = "hello"
s[0] = "H" # TypeError! Strings are immutable
s = "Hello" # Creates new string objectlst = [1, 2, 3]
lst[0] = 99 # OK! Lists are mutable
lst.append(4)class Animal:
# Class variable
kingdom = "Animalia"
# Constructor
def __init__(self, name, sound):
self.name = name # instance variable
self.sound = sound
# Method
def speak(self):
return f"{self.name} says {self.sound}"
# Class method
@classmethod
def get_kingdom(cls):
return cls.kingdom
# Inheritance
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")
# Override
def speak(self):
return f"Dog {self.name}: Woof Woof!"
d = Dog("Buddy")
print(d.speak()) # Dog Buddy: Woof Woof!
print(d.get_kingdom()) # Animalia