KEMBAR78
Top 300 Python Interview Q&A | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
17 views40 pages

Top 300 Python Interview Q&A

The document is a comprehensive list of the top 300 Python interview questions categorized into various topics such as core fundamentals, control flow, object-oriented programming, and more. Each section contains specific questions along with concise answers covering key concepts and features of Python. Additionally, it includes links to social media for further content and job updates.

Uploaded by

shanurudra177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views40 pages

Top 300 Python Interview Q&A

The document is a comprehensive list of the top 300 Python interview questions categorized into various topics such as core fundamentals, control flow, object-oriented programming, and more. Each section contains specific questions along with concise answers covering key concepts and features of Python. Additionally, it includes links to social media for further content and job updates.

Uploaded by

shanurudra177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Top 300

Python Interview Questions

• Core Fundamentals (1–15)


• Control Flow & Functions (16–30)
• Object-Oriented Programming (31–50)
• Exception Handling, File I/O (51–70)
• Modules, Packages, Virtual Environments (71–90)
• Standard Library, Useful Modules (91–100)
• Data Structures, Algorithms, and Patterns (101–130)
• Advanced Functions, Iterators, Generators (131–160)
• Strings, Encoding, and Regular Expressions (161–180)
• Numbers, Math, Random, Dates (181–200)
• Pythonic Idioms & Best Practices (201–220)
• Comprehensions & Generators (221–240)
• Concurrency & Parallelism (241–270)’
• Web Development & Networking (271–290)
• Testing, Debugging & Packaging (291–300)

Join us for more such content and job updates


YouTube - https://youtube.com/@bangontheory

Instagram - https://www.instagram.com/jobtechmingle

Telegram - https://t.me/jobtechmingle

Whatsapp - https://whatsapp.com/channel/0029VaDSmuKATRShykIO133V
Core Fundamentals (1–15)

1. What is Python and why is it popular?

Python is a high-level, interpreted programming language renowned for its clean syntax, vast libraries,
and strong community support.
Popularity reasons: readability, ease of learning, cross-platform, “batteries included”, supports multiple
programming paradigms (procedural, object-oriented, functional).

2. Name major features of Python.

• Interpreted and dynamically typed

• Simple, readable syntax

• Large standard library

• Portable (runs on all platforms)

• Object-oriented and functional

• Extensible via modules and packages

3. What are Python’s built-in data types?

• Numeric: int, float, complex

• Sequence: str, list, tuple

• Collection: set, frozenset, dict

• Boolean: bool

• NoneType: None
4. What is PEP 8?

PEP 8 is the official Python style guide. It prescribes code formatting rules (indentation, naming, line
length, etc.) for readable and consistent code.

5. What is the difference between list and tuple?

List Tuple

Mutable Immutable

Defined by [ ] Defined by ( )

Slower, more flexible Faster, hashable

6. What is a dictionary in Python?

A dictionary is a collection of key-value pairs.


Keys must be unique and immutable.
Example:

person = {'name': 'Alice', 'age': 30}

7. What is a set and why is it useful?

A set is an unordered collection of unique elements, ideal for membership tests and removing duplicates.
Example:

nums = {1, 2, 3, 3} # {1, 2, 3}

8. Explain mutability in Python.

• Mutable objects can be changed: list, dict, set

• Immutable objects cannot: int, str, tuple, frozenset

9. How does Python handle arguments (pass by reference/value)?


Python uses pass-by-object-reference:

• Mutable arguments can be changed in-place inside functions

• Immutable arguments produce a new object if changed

10. What is slicing?

Slicing extracts parts of sequences like lists and strings.


Example:

arr[1:4] # Returns items at index 1, 2, 3

11. How do you reverse a list or string?

lst[::-1] # reverse list


s[::-1] # reverse string

Or use .reverse() for a list (in-place).

12. What is list comprehension?

A concise way to create lists.

squares = [x*x for x in range(5)]

13. How do you copy a list?

• Shallow copy: lst.copy(), lst[:], or copy.copy(lst)

• Deep copy: copy.deepcopy(lst)

14. Difference between == and is?

• ==: value equality

• is: object identity (same memory address)

15. How to check type of a variable?


• type(x)

• isinstance(x, t)

Control Flow & Functions (16–30)

16. How do you write an if-else statement?

if x > 0:
print('Positive')
elif x == 0:
print('Zero')
else:
print('Negative')

17. List loop types in Python.

• for (over a sequence)

• while (until condition false)

• Control: break, continue, else with loops

18. How do you iterate over both index and value in a list?

for i, v in enumerate(mylist):
print(i, v)

19. How do you define a function?

def add(a, b=0):


return a + b

**20. What are *args and kwargs?


• *args: variable number of positional arguments (tuple)

• **kwargs: variable number of keyword arguments (dict)

def f(*args, **kwargs): pass

21. What is a lambda function?

An anonymous inline function.

add = lambda x, y: x + y

22. What does the return statement do?

Exits a function and optionally returns a value.


If no return, function returns None.

23. How can you give a function default parameters?

def greet(name, likes="Python"):


print(f"Hi, {name}! Do you like {likes}?")

24. What is recursion?

A function that calls itself, usually to break a problem into smaller subproblems.

def fact(n):
return 1 if n==0 else n*fact(n-1)

25. What is a decorator?

A function that modifies/enhances another function.

def deco(f):
def wrapper(*a, **k):
print('Before')
v = f(*a, **k)
print('After')
return v
return wrapper

@deco
def foo(): pass

26. What does map() do?

Applies a function to every item in an iterable.

list(map(str, [1, 2]))

27. How do you filter elements in a sequence?

Using filter(func, seq), returning elements for which func is True.

even = list(filter(lambda x: x % 2 == 0, [1,2,3,4]))

28. What does zip() do?

Combines multiple sequences element-wise into tuples.

pairs = list(zip([1,2], ['a','b'])) # [(1,'a'), (2,'b')]

29. What is a generator?

A function using yield to lazily produce sequence values.

def gen():
for i in range(3): yield i

30. How do you handle exceptions?

try:
1/0
except ZeroDivisionError:
print("Division by zero!")
finally:
print("Done.")

Object-Oriented Programming (31–50)

31. What is object-oriented programming?

A paradigm modeling programs as collections of objects—structures bundling data (attributes) and


behavior (methods) for modular, reusable code.

32. How do you define a class in Python?

class Car:
def __init__(self, make):
self.make = make

33. What is self in a Python class?

The reference to the current instance, allowing access to attributes and methods.

34. What is __init__?

The constructor method called when an object is created to initialize its attributes.

35. What is inheritance?

Allows a class (child) to inherit attributes and methods from another class (parent).

36. Example of class inheritance:

class Animal: pass


class Dog(Animal): pass

37. What is method overriding?

Redefining a parent method in a child class with a new implementation.


38. What's the difference between class and instance variables?

• Class variables shared among all instances

• Instance variables unique to each instance

39. What are magic methods?

Special methods with double underscores (e.g. __str__, __add__). They enable operator overloading and
language features.

40. How to use __str__ and __repr__?

• __str__: Human-readable string (str(obj))

• __repr__: Unambiguous debugger string (repr(obj))

41. What is encapsulation?

Hiding implementation details via naming conventions (_protected, __private) and restricting direct
access.

42. What is polymorphism?

Different objects can be accessed through a common interface, enabling functions to process objects of
different classes uniformly.

43. What is an abstract base class (ABC)?

A class that can’t be instantiated; defines interface for subclasses.


Use abc and @abstractmethod.

44. Difference between static, instance, and class methods?

• Static: No access to self/cls, use @staticmethod

• Class: Access to class as cls, use @classmethod

• Instance: Access to self, default method type

45. Usage of super()?

Access and call parent class methods/attributes, especially in inheritance:


class Sub(Base):
def __init__(self):
super().__init__()

46. What is a property in Python?

A way to use methods as attributes with @property decorator. Enables getter/setter logic.

@property
def area(self):
return self.radius**2 * 3.14

47. How do you make a class iterable?

Implement __iter__ (returns iterator) and optionally __next__.

48. What is operator overloading?

Customizing an object’s behavior with operators by defining magic methods (e.g., __add__, __eq__).

49. What is multiple inheritance?

A class inheriting from more than one parent class.

class C(A, B): pass

50. What is duck typing?

If an object implements required methods/attributes, it can be used regardless of its type ("If it walks like
a duck...").

Exception Handling, File I/O (51–70)

51. How do you raise an exception?

raise ValueError("Invalid value")

52. How do you catch multiple exception types?


try:
...
except (ValueError, TypeError):
...

53. What is the finally block for?

Executes regardless of exceptions. Use for clean-up (closing files, etc.).

54. What’s a context manager?

Handles resource setup and clean-up. Methods: __enter__, __exit__. Used with with.

55. Example of a custom context manager:

class Managed:
def __enter__(self): ...
def __exit__(self, exc_type, exc_val, exc_tb): ...

Or use contextlib.contextmanager:

from contextlib import contextmanager


@contextmanager
def managed():
...
yield
...

56. How do you open and write to a file?

with open('file.txt', 'w') as f:


f.write("Text")

57. How to read a file, all at once and line by line?

• All: f.read()

• Line by line: for line in f: ...


58. How do you append to a file?

Open with "a" mode: open('file.txt', 'a')

59. How to delete a file?

import os
os.remove('file.txt')

60. How to check if a file exists?

import os
os.path.exists('file.txt')

61. What's the purpose of with open(...) as f?

Ensures file is closed automatically (context manager pattern).

62. What is serialization (pickling)?

Storing Python objects to disk as bytes with pickle; unpickle to recover.

import pickle
pickle.dump(obj, file)
obj = pickle.load(file)

63. How to read/write CSV files?

Use the csv module.

import csv
with open('f.csv') as f:
reader = csv.reader(f)
for row in reader: ...

64. How do you parse JSON in Python?

import json
data = json.loads(s)
s = json.dumps(data)

65. How do you handle Unicode in files?

Specify encoding:

open('file.txt', encoding='utf-8')

66. How do you open a file for both reading and writing?

Open with "r+" mode: open('file.txt', 'r+')

67. What is the difference between read(), readline(), readlines()?

• read(): whole file as string

• readline(): one line as string

• readlines(): all lines as list

68. How do you get the current working directory?

import os
os.getcwd()

69. How do you list files in a directory?

import os
os.listdir('path')

70. How to copy/move files?

Use the shutil module:

import shutil
shutil.copy('f1', 'f2')
shutil.move('f1', 'dir2/')

Modules, Packages, Virtual Environments (71–90)

71. What is a Python module?

A file containing Python definitions, functions, and classes.


Import with import module_name

72. What is a package?

A directory with an __init__.py file; organizes and groups modules.

73. How do you import code from another module or package?

# In same directory
import mod
from mod import func

# In a package
from pkg.mod import func

74. What does __name__ == '__main__' mean?

True if the script is run directly (not imported as a module), used for main routines.

75. How do you install packages from PyPI?

Via pip: pip install package

76. How do you list installed packages?

pip list

77. What is a virtual environment?

A self-contained Python environment for installing packages without affecting the global Python install.
78. How to create and activate a venv?

python -m venv env


source env/bin/activate # Linux/macOS
env\Scripts\activate # Windows

79. How do you freeze and export dependencies?

pip freeze > requirements.txt

80. How to install dependencies from a requirements file?

pip install -r requirements.txt

81. What does __init__.py do?

Turns a folder into a package; can run initialization code.

82. How do you perform absolute and relative imports?

• Absolute: from pkg.module import obj

• Relative: from . import sibling (within same package)

83. What is PYTHONPATH?

An environment variable specifying search paths for module imports.

84. How to find where a module is installed?

import module
print(module.__file__)

85. How to run a script from the command line?

python script.py

86. How do you pass command-line arguments?

Use sys.argv (list of strings, script name + arguments).


87. How to parse complex command line arguments?

Use the argparse module.

88. How do you get all environment variables?

import os
os.environ

89. How do you set an environment variable?

os.environ['VAR'] = 'value'

90. How do you reload a module at runtime?

import importlib
importlib.reload(module)

Standard Library, Useful Modules (91–100)

91. What is the os module for?

Interacting with the operating system: paths, files, processes, environment.

92. What is the sys module for?

Tooling for interpreter interaction (argv, exit, path for imports, etc.)

93. What does the collections module offer?

Specialized data structures: deque, namedtuple, Counter, defaultdict, OrderedDict.

94. What does the re module do?

Regular expressions: pattern matching/search/replace.

95. What is the random module used for?

Random numbers, sampling, shuffling, etc.


96. What does the datetime module provide?

Date and time manipulation.

97. How do you measure code execution time?

• time.time() for simple intervals

• timeit module for precise measurement

98. How do you log messages in Python?

Use the logging module:

import logging
logging.warning("This is a warning")

99. What is the purpose of the math module?

Mathematical functions: sqrt, trigonometry, constants (pi, e), etc.

100. What is the functools module for?

Higher-order functions and tools: reduce, lru_cache (memoization), partial, etc.

Data Structures, Algorithms, and Patterns (101–130)

101. What is a namedtuple and why is it useful?

A namedtuple (from collections) is an immutable tuple with named fields for readable, self-
documenting code.

from collections import namedtuple


Point = namedtuple('Point', 'x y')
p = Point(1, 2) # Access: p.x, p.y

102. What is a defaultdict?

A defaultdict assigns a default value if a missing key is accessed, avoiding KeyErrors.


from collections import defaultdict
d = defaultdict(int); d['x'] += 1 # d['x'] == 1

103. Use-case for Counter.

Counter counts occurrences of hashable items (from collections).

from collections import Counter


c = Counter('banana') # Counter({'a':3, 'n':2, 'b':1})

104. What is a deque and how does it differ from a list?

A deque is a double-ended queue with O(1) appends/pops from both ends, unlike lists which are fast only
at the end.

from collections import deque


dq = deque([1,2,3]); dq.appendleft(0)

105. OrderedDict vs dict?

Pre-Python 3.7, OrderedDict preserved insertion order, which standard dict now does (since 3.7).
OrderedDict still provides extra features.

106. How do you remove duplicates from a list?

Use set() or, to preserve order: list(dict.fromkeys(lst)).

107. How do you flatten a list of lists?

flat = [item for sublist in lst for item in sublist]

108. How do you merge two lists?

merged = list1 + list2 or list1.extend(list2)

109. How to swap variable values?


a, b = b, a

110. How to reverse a dictionary (swap keys and values)?

reversed_dict = {v: k for k, v in orig.items()}

111. What does enumerate() do?

Provides index and value during iteration.

for i, v in enumerate(['a','b','c']): ...

112. How can you sort a dictionary by value?

sorted_dict = dict(sorted(d.items(), key=lambda x: x[1]))

113. What is zip(*) used for?

Transposes a list of tuples (matrix transpose).

zip(*[(1,2), (3,4)]) # (1,3), (2,4)

114. How do you check if all elements in a list are unique?

len(set(lst)) == len(lst)

115. How to count unique elements in a list?

len(set(lst)) or Counter(lst)

116. What is the bisect module?

Efficient insertion/lookup in sorted lists via binary search.

117. How to shuffle a list randomly?


import random
random.shuffle(lst)

118. How to implement a stack in Python?

Use a list: push with .append(x), pop with .pop().

119. How to implement a queue in Python?

• For FIFO: use collections.deque: .append(x) and .popleft()

120. What is a heap and how is it used in Python?

A binary heap (min-heap) via heapq.


For efficient min item retrieval/insertion.

121. How do you reverse a string?

s[::-1]

122. Check if a string is a palindrome.

s == s[::-1]

123. Remove all whitespace in a string.

s.replace(" ", "")

124. Remove leading/trailing whitespace.

s.strip()

125. Split a string by a character?

s.split(',')

126. Join a list of strings into one string.

' '.join(lst)

127. Find the most common element in a list.


from collections import Counter
Counter(lst).most_common(1)[0][0]

128. Capitalize each word in a string.

s.title()

129. Reverse the order of words in a string.

' '.join(s.split()[::-1])

130. How do you check if a list contains a value?

x in lst

Advanced Functions, Iterators, Generators (131–160)

131. What is a generator expression?

Like a list comprehension, but returns an iterator.

gen = (x*x for x in range(10))

132. How do you create a custom iterator?

Implement __iter__() (returns self) and __next__() methods.

133. How do you use next() with iterators?

it = iter([1, 2, 3])
val = next(it) # Gets next item

134. How do you check if an object is iterable?

Try iter(obj) or check hasattr(obj, '__iter__')

135. What is functools.reduce()?

Reduces a sequence to a single value using a binary function.


from functools import reduce
reduce(lambda x, y: x + y, [1, 2, 3])

136. When should you use partial()?

To “pre-fill” arguments of a function, creating a new callable.

from functools import partial


pow2 = partial(pow, exp=2)

137. What is @lru_cache?

A built-in decorator for memoizing function results.

from functools import lru_cache


@lru_cache
def fib(n): ...

138. How do you write a function that accepts any number of arguments?

Use *args and **kwargs.

139. What does * and ** mean in function calls?

• * unpacks sequences (positional)

• ** unpacks dicts (keyword)

140. How do you handle missing function arguments?

Set default values in parameters.

141. What is a closure?

A nested function that captures variables from its enclosing scope.

def outer():
x = 1
def inner():
print(x)
return inner

142. How do you define a decorator that accepts arguments?

One extra nesting level:

def deco(arg):
def wrapper(func):
...
return wrapped
return wrapper

143. What is the difference between a shallow and deep copy?

• Shallow: copies outer object, not inner objects.

• Deep: recursively copies all objects inside.

144. How do you make a function a property of a class?

Use @property decorator.

145. What does the built-in function all() do?

Returns True if all elements of an iterable are true.

146. What does any() do?

Returns True if any element is true.

147. What is a docstring?

A string literal documenting a module, class, or function; accessible via help() and .__doc__.

148. How do you format strings in Python 3?

• Old: "{} {}".format(a, b)

• f-strings (3.6+): f"{a} {b}"

149. Difference between % formatting and f-string?


• %-format: older, less readable, less efficient

• f-string: newer, more concise/faster, can embed expressions

150. How to add methods to a class after defining it?

Assign function as attribute:

def speak(self): print("Hi")


MyClass.speak = speak

151. How to convert a list of strings to a list of ints?

list(map(int, str_list))

152. What does the del statement do?

Removes references (variables or object items).

153. What is chain() in itertools?

Combines multiple iterables into one sequence.

154. What is itertools.groupby()?

Groups consecutive duplicate items together.

155. How do you count elements in an iterator without storing them?

Use sum(1 for _ in iterator)

156. How do you generate combinations/permutations?

itertools.combinations(iterable, r) / itertools.permutations(iterable, r)

157. What does enumerate() return?

An iterator of (index, value) pairs.

158. What happens if you yield from inside a function?

It returns a generator.
159. Difference: yield vs return?

• return ends function, returns a value

• yield produces a value and pauses function state for next call

160. What is the difference between xrange and range?

range in Python 3 is like xrange in Python 2: it produces an iterator and is memory efficient.

Strings, Encoding, and Regular Expressions (161–180)

161. What’s the difference between bytes and str?

• str: Unicode text

• bytes: Sequences of raw bytes

162. How do you encode and decode a string?

s = 'hi'
b = s.encode('utf-8')
s2 = b.decode('utf-8')

163. How do you read/write Unicode files?

Pass encoding='utf-8' to open().

164. How do you check if a string contains a substring?

'foo' in s

165. How do you find/replace substrings?

.find(), .replace()

s.replace('old', 'new')

166. How do you split a string by whitespace?

s.split()
167. How do you strip specific characters from a string?

s.strip(chars)

168. Difference between isdigit(), isnumeric(), isdecimal()?

All check if a string represents numbers, but isnumeric/isdecimal include more Unicode numerals.

169. What is the re module?

Provides regular expressions for pattern matching.

170. How do you search for a pattern in a string?

import re
if re.search(r'\d+', text):
print('Contains a number')

171. How do you replace with regex?

new = re.sub(r'\d+', 'num', text)

172. How do you extract all matches of a pattern?

re.findall(pattern, string)

173. What are raw strings and why use them in regex?

Prefix with r'' to avoid escape processing: r'\n' is two characters, not a newline.

174. How do you match the beginning/end of a string in regex?

^pattern (start), pattern$ (end)

175. How do you group patterns in regex?

With parentheses: (pattern)

176. What does re.compile() do?

Pre-compiles a regex pattern for efficient repeated use.


177. How do you split a string by regex?

re.split(pattern, string)

178. How do you substitute matched content with a function?

re.sub(pattern, func, string)

179. How to find all words in text with regex?

re.findall(r'\w+', text)

180. How do you count the frequency of words in a text?

from collections import Counter


Counter(re.findall(r'\w+', text))

Numbers, Math, Random, Dates (181–200)

181. How do you round a float?

round(num, digits)

182. How do you format a float with 2 decimals?

f"{x:.2f}" or "%.2f" % x

183. What does // operator do?

Integer (floor) division.

184. How to generate random numbers?

import random
random.randint(1, 10)
random.random() # [0, 1)

185. How do you select a random item from a list?

random.choice(lst)
186. How do you get unique random samples from a list?

random.sample(lst, k)

187. How do you shuffle a list in-place randomly?

random.shuffle(lst)

188. What’s the difference between math.trunc(), floor(), ceil()?

• trunc: rounds toward zero

• floor: rounds down

• ceil: rounds up

189. How do you get current time/date?

import datetime
now = datetime.datetime.now()
today = datetime.date.today()

190. How do you parse/format dates?

dt = datetime.datetime.strptime("2023-01-01", "%Y-%m-%d")
dt.strftime("%d/%m/%Y")

191. How do you do timedeltas/date arithmetic?

from datetime import timedelta


dt + timedelta(days=1)

192. How do you get the day of week of a date?

dt.weekday() (Monday=0) or dt.strftime("%A") (name)

193. How do you convert UTC to local time and vice versa?

Use pytz module or datetime.timezone


194. How do you time code execution?

import time
start = time.time()
# code
elapsed = time.time() - start

195. How do you generate random floats in a range?

random.uniform(a, b)

196. How do you seed the random number generator?

random.seed(val)

197. How do you handle decimal precision accurately?

Use the decimal module.

from decimal import Decimal


Decimal('0.1') + Decimal('0.2')

198. How do you calculate factorial, gcd, lcm?

Use math.factorial(n), math.gcd(a, b), math.lcm(a, b).

199. How do you get the absolute value of a number?

abs(x)

200. How do you convert between number bases (bin/oct/hex)?

Use bin(x), oct(x), hex(x) for string representation. int(s, base) for parsing.

Pythonic Idioms & Best Practices (201–220)

201. What does “Pythonic” mean?

Code that follows Python language conventions, idiomatic style, and readability goals.
202. How do you swap two variables without a temp?

a, b = b, a

203. What is the difference between isinstance() and type()?

• isinstance(obj, Class) checks inheritance hierarchy

• type(obj) == Class checks exact type only

204. How do you check if a list is empty?

if not my_list:
# empty

205. How to read environment variables in Python?

import os
val = os.getenv('VAR_NAME', 'default')

206. What is EAFP? (Easier to Ask for Forgiveness than Permission)

Pythonic style favoring try-except over pre-checks.

207. What is LBYL?

“Look Before You Leap” — checking conditions before operations (less Pythonic).

208. How do you check if a key exists in a dict?

if 'key' in d:
...

209. How to merge two dictionaries in Python 3.9+?

merged = dict1 | dict2

210. What is “duck typing” in Python?


Type compatibility based on methods/attributes an object implements, not its explicit class.

211. How do you concatenate strings efficiently?

Use str.join() instead of repeated concatenation in loops.

212. How to handle numeric precision with float?

Use the decimal module for precise decimal arithmetic.

213. How do you unpack lists/tuples into variables?

a, b, c = (1, 2, 3)

214. How to use starred expressions to capture multiple items?

a, *rest = [1, 2, 3, 4] # a=1, rest=[2,3,4]

215. What’s a Python “slice”?

Accessing parts of sequences via [start:stop:step].

216. How to reverse a list or string?

s[::-1]

217. How can you chain comparison operators?

if 0 < x < 10:


...

218. How to get unique values keeping order?

list(dict.fromkeys(mylist))

219. How can you copy an object?

Use shallow copy with copy.copy(), deep copy with copy.deepcopy().


220. How to check if a number is even?

if num % 2 == 0:
...

Comprehensions & Generators (221–240)

221. What is a list comprehension?

Concise syntax for creating lists.

squared = [x**2 for x in range(10)]

222. How are generator expressions different?

They produce items lazily (on demand), saving memory.

gen = (x**2 for x in range(10))

223. How to write a dictionary comprehension?

squares = {x: x*x for x in range(5)}

224. What is “lazy evaluation”?

Delay computation until result is needed (used in generators).

225. How do generators improve performance?

By yielding one item at a time instead of storing entire sequence.

226. How to chain multiple iterators?

Use itertools.chain()

227. How do you filter with list comprehension?

even = [x for x in numbers if x % 2 == 0]


228. What are generator functions?

Functions using yield to return an iterator with paused state.

229. How do you consume a generator?

Use next(gen) or a loop.

230. How to create an infinite generator?

def count():
n = 0
while True:
yield n
n +=1

231. How to handle StopIteration?

Catch it or use a for loop.

232. What is the difference between iterator and iterable?

• Iterable: has __iter__() method

• Iterator: has __next__() method and state

233. How do you implement an iterator?

Define class with __iter__() returning self and __next__() returning next item or raising
StopIteration.

234. What is yield from?

Delegates part of generator to subgenerator.

235. Can generators be nested?

Yes.

236. How can you send values into a generator?

Using generator.send(value).
237. How do you close a generator?

Call generator.close().

238. How do you throw exceptions into a generator?

Use generator.throw(ExceptionType).

239. When to use generators over lists?

For large or infinite sequences or when memory efficiency is critical.

240. What is functools.partial used for?

To fix some portion of arguments and generate a new callable.

Concurrency & Parallelism (241–270)

241. What is threading in Python?

Lightweight concurrency, multiple threads share memory.

242. What does the Global Interpreter Lock (GIL) do?

Prevents multiple native threads from executing Python bytecodes simultaneously in one process.

243. How do you create a thread?

import threading
thread = threading.Thread(target=func)
thread.start()

244. What is the multiprocessing module?

Allows true parallel processes bypassing GIL.

245. When to use threading vs multiprocessing?

• Threading: I/O-bound tasks

• Multiprocessing: CPU-bound tasks


246. What is an event loop?

Central loop in async programming managing task scheduling.

247. What is asyncio?

Python's built-in asynchronous I/O framework using coroutines.

248. How do you define an async function?

async def foo():


await some_async_call()

249. How do you run async code?

Use asyncio.run() or get event loop.

250. What are coroutines?

Functions declared with async def which can pause and resume.

251. What is a Future in asyncio?

Represents a result that may be available later.

252. Difference between threads and processes?

Threads share memory space; processes have separate memory.

253. What are locks and why use them?

Locks synchronize access to shared resources to prevent race conditions.

254. How do you use a lock in threading?

lock = threading.Lock()
with lock:
# critical section

255. What is a deadlock?


Multiple threads waiting indefinitely for each other’s resources.

256. How do you avoid deadlocks?

• Acquire locks in consistent order

• Use timeout in locks

• Minimize lock scope

257. What is a thread pool?

Pool of worker threads to execute async tasks.

258. What is concurrent.futures?

High-level interface for asynchronously executing callables.

259. What is a semaphore?

Limits number of simultaneous accesses to a resource.

260. How do you implement producer-consumer with queue?

Use queue.Queue() with threads.

261. What is the difference between blocking and non-blocking calls?

Blocking waits until completion; non-blocking returns immediately.

262. What’s GIL’s impact on concurrency?

Limits parallel CPU-bound Python code on a single process.

263. What is an executor in concurrent.futures?

Manages running tasks asynchronously (ThreadPoolExecutor/ProcessPoolExecutor).

264. How to cancel async tasks?

Use task.cancel().

265. How to wait for multiple futures?


asyncio.gather() or concurrent.futures.wait().

266. What are tasks in asyncio?

Scheduled coroutines wrapped for control.

267. What does await keyword do?

Pauses coroutine until awaited future completes.

268. Difference between concurrency and parallelism?

Concurrency: multiple tasks progress without simultaneous execution; parallelism: tasks execute
simultaneously.

269. What are callbacks and how are they used?

Functions passed as arguments to be called later (e.g., event handlers).

270. What is the difference between process and thread pools?

Process pools run tasks in separate processes; thread pools use threads.

Web Development & Networking (271–290)

271. How do you create a basic HTTP server in Python?

Use http.server module.

272. What libraries are popular for web development in Python?

• Flask

• Django

• FastAPI

273. What is WSGI?

Web Server Gateway Interface – spec for Python web frameworks and servers.

274. How to send HTTP requests?


Use requests library.

275. How to parse URLs?

Use urllib.parse.urlparse().

276. How do you implement routing in Flask?

@app.route('/hello')
def hello():
return 'Hello'

277. How to handle query parameters in Flask?

Use request.args.

278. How to send JSON response in Flask?

Use jsonify().

279. What is middleware in web frameworks?

Code that runs between request and response, e.g., auth, logging.

280. What is REST API?

Representational State Transfer – web APIs using HTTP methods.

281. How to handle sessions in Flask?

Using flask.session module with secret key.

282. How to manage user authentication?

Use libraries like Flask-Login or Django auth.

283. How to serve static files in Flask?

Place in static/ and use url_for('static', filename='...').

284. What is CORS and how to handle it?


Cross-Origin Resource Sharing; handled with appropriate headers or Flask-CORS.

285. How do you test Flask applications?

Use Flask’s test client with app.test_client().

286. What is WebSocket?

Full duplex communication over a single TCP connection.

287. How to implement WebSocket in Python?

Use websockets or aiohttp.

288. How to parse JSON in request body?

data = request.get_json()

289. How to upload files using Flask?

Use request.files.

290. How to run a Python script as a daemon?

Use libraries like daemonize, or write a system service.

Testing, Debugging & Packaging (291–300)

291. What is unittest in Python?

Python’s built-in testing framework supporting test cases, suites, assertions.

292. How do you write a test with unittest?

import unittest

class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(1+1, 2)
293. How do you run unittests?

python -m unittest discover

294. What is pytest?

A third-party, powerful testing framework with easier syntax and plugins.

295. How to skip a test?

Use @unittest.skip or @pytest.mark.skip.

296. What is mocking?

Replacing parts of your system under test with mock objects.

297. How do you debug Python code?

Using pdb debugger or IDE debuggers; insert import pdb; pdb.set_trace().

298. What is logging and why use it?

Replace print statements for production logging with levels and handlers.

299. How to create a Python package?

Organize code in directories with __init__.py, write setup.py for distribution.

300. How to distribute Python packages?

Use setuptools to build and upload to PyPI.

You might also like