Python
Python Interview Questions and Answers
1. What is Python?
Python is a high-level, interpreted, and general-purpose programming language known for its readability and dynamic typing.
2. What are Python’s key features?
- Easy to learn and read
- Interpreted
- Dynamically typed
- Extensive standard libraries
- Object-oriented and functional
3. What are Python’s data types?
- Numeric: int, float, complex
- Sequence: list, tuple, range
- Text: str
- Set: set, frozenset
- Mapping: dict
- Boolean: bool
- NoneType: None
4. What is a dynamically typed language?
Variable types are determined at runtime.
5. What is PEP 8?
It is the style guide for writing clean and readable Python code.
6. What is the difference between is and ==?
is
: compares identity==
: compares values
7. How is memory managed in Python?
- Through reference counting and garbage collection.
8. What is the difference between a list and a tuple?
- List: mutable
- Tuple: immutable
9. What is a dictionary in Python?
- An unordered collection of key-value pairs:
10. How do you comment in Python?
Single line: # Comment
Multi-line: """Comment"""
or '''Comment'''
11. What are Python control structures?
if
, elif
, else
, for
, while
, break
, continue
, pass
12. How to define a function in Python?
python def greet(name): return f"Hello, {name}"
13.W hat is a lambda function?
- Anonymous function:
14. What are *args
and kwargs?
*args
: variable-length positional arguments
*kwargs
: variable-length keyword arguments
15. What is recursion?
- A function calling itself.
16. What is the purpose of return?
- It ends the function and sends a result back.
17. What is pass?
- A placeholder for future code.
18. What is the use of yield?
- It turns a function into a generator.
19. What’s the difference between global
and nonlocal
?
global
: refers to variables in the global scopenonlocal
: refers to variables in the enclosing scope
20. What is a docstring?
- Documentation string used for functions, classes, or modules.
21. What is OOP?
- Object-Oriented Programming, based on objects and classes.
22. What is a class?
- A blueprint for creating objects.
23. What is an object?
- An instance of a class.
24. What are __init__
and self
?
__init__
: constructorself
: refers to the instance itself
25. What is inheritance?
- Reusing code from parent classes.
26. What is multiple inheritance?
- A class inheriting from multiple classes.
27. What is encapsulation?
- Hiding internal details using private members (
_var
,__var
).
28. What is polymorphism?
- Different classes having methods with the same name.
29. What are magic methods?
- Special methods like
__str__
,__len__
,__add__
.
30. What is a class method and static method?
@classmethod
: works with class, takes cls@staticmethod
: does not access class or instance data
31. How to open a file in Python?
32. How to read/write
a file?
Read
: f.read()Write
: f.write("data")
33.. What is with open()?
- It auto-closes files.
34. What is a module?
- A Python file with functions and classes.
35. What is a package?
- A directory containing
__init
__.pyand
modules`.
36. How to import a module?
37. How to list installed modules?
- Use pip list
38. What is the difference between import and from?
- import os vs from os import path
39. How to install packages?
- pip install package_name
40. How to create a virtual environment?
41. What is an exception?
An error that disrupts normal program flow.
42. How to handle exceptions?
43. What is finally used for?
- Executes code regardless of exception.
44. What is the use of raise?
- To manually raise an exception.
45. Name some common exceptions.
ValueError
,IndexError
,TypeError
,KeyError
46. What is assert?
- Used to debug, raises AssertionError if condition is False.
47. How to debug in Python?
- Using pdb or IDE debuggers.
48. What is traceback?
- Error report showing where an exception occurred.
49. How to log errors?
- Using the logging module.
50. What is the difference between error and exception?
Error
: programming mistakeException
: can be handled
51. What is a generator?
- Function that returns an iterator using yield.
52. What is a decorator?
- Function that modifies another function.
53. What are comprehensions?
- Compact ways to create collections.
54. What is a context manager?
- Object with
__enter__ 1and
exit` methods. Used in with.
55. What is a metaclass?
- A class of a class.
56. What is duck typing?
- Type checking based on behavior not inheritance.
57. What is monkey patching?
- Changing a class or module at runtime.
58. What is GIL (Global Interpreter Lock
)?
- A lock that allows only one thread to execute at a time in CPython.
59. What is multithreading?
- Running multiple threads concurrently.
60. What is multiprocessing?
- Running code in multiple processes for true parallelis
61. What is a list?
- Ordered, mutable collection.
62. What is a tuple?
- Ordered, immutable collection.
63. What is a set?
- Unordered, unique items.
64. What is a dictionary?
- Key-value pairs.
65. How to merge two lists?
66. How to sort a list?
sorted(list)
orlist.sort()
67. What is a shallow copy vs deep copy?
- Shallow: one level deep
- Deep: full recursive copy
68. How to reverse a list?
list[::-1]
orlist.reverse()
69. How to remove duplicates?
list(set(mylist))
70. How to iterate over a dictionary?
71. What is NumPy used for?
- Efficient numerical and matrix operations.
72. What is pandas?
- Data manipulation library using DataFrames.
73. What is matplotlib?
- For data visualization.
74. What is Flask?
- A micro web framework.
75. What is Django?
- A high-level full-stack web framework.
76. What is SQLAlchemy?
- ORM for databases in Python.
77. What is pip?
- Python package manager.
78. What is Jupyter Notebook?
- Web-based IDE for interactive Python.
79. What is virtualenv?
- Tool to create isolated Python environments.
80. What is pytest?
- A testing framework.
81. What is slicing?
- Extracting parts of strings, lists, etc.
82. How to check Python version?
python --version
83. What is __name__ == "__main__"
used for?
- Entry point of a script.
84. What is list comprehension?
- Compact list creation:
85. What is the walrus operator :=
?
- Assignment expression inside conditions (Python 3.8+).
86. What are f-strings?
- Formatted string literals:
87. How to convert string to int?
int("123")
88. How to convert int to string?
str(123)
89. What is a ternary operator?
90. What is dir()
?
- Lists attributes of object.
91. Swap two variables.
92. Check if string is palindrome.
93. Factorial using recursion.
94. Fibonacci series.
95. Check for prime.
96. Reverse a string.
97. Sum of list.
98. Find max in list.
99. List even numbers from list.
101. How do you create a string in Python?
102. How do you concatenate strings?
103. How to repeat a string 3 times?
104. How to find the length of a string?
105. How to convert to uppercase/lowercase?
106. How to check if a string starts/ends with a substring?
107. How to find a substring in a string?
108. How to replace part of a string?
109. How to split a string?
110. How to join a list into a string?
111. How to strip whitespace from a string?
112. How to check if string is digit?
113. How to reverse a string?
114. What is a raw string?
- A string with
r""
to ignore escape sequences.
115. How to format a string with variables?
116. ### What does zfill()
do?
- Pads string on the left with zeros:
"5".zfill(3) → "005"
117. How to count substrings?
118. What is isalnum()
?
- Checks if string is alphanumeric.
119. How to center a string?
120. What’s the difference between isalpha()
and isdigit()
?
isalpha()
: checks for lettersisdigit()
: checks for digits
121. How to add item to a list?
122. How to insert item at specific index?
123. How to remove an item by value?
124. How to remove an item by index?
125. How to copy a list?
126. How to flatten a nested list?
127. How to use enumerate?
128. What does any()
do?
- Returns True if at least one element is truthy.
129. What does all()
do?
- Returns True if all elements are truthy.
130. How to check if a list is empty?
131. Difference between list()
and []
?
list()
can convert iterables;[]
creates a literal list.
132. How to remove duplicates but keep order?
133. What is the difference between sort()
and sorted(
)?
sort()
modifies list in-placesorted()
returns a new list
134. How to zip two lists?
135. How to unpack a list?
136. What does reversed()
do?
- Returns an iterator to reverse the sequence.
137. What is the use of map()
?
- Applies a function to all items:
138. What does filter()
do?
- Filters elements based on a function.
139. What does reduce()
do?
- Applies function cumulatively to the list (from functools).
140. How to use list comprehension with condition?
141. How to create a tuple?
142. What’s tuple unpacking?
143. Are tuples hashable?
- Yes, if they contain only immutable elements.
144. How to convert list to tuple?
145. What is a frozenset?
- Immutable set.
146. What are set operations?
union()
, intersection()
, difference()
, symmetric_difference()
147. How to check subset/superset?
148. What is a dictionary comprehension?
149. How to merge two dictionaries?
150. How to get keys/values/items from dict?
151. What is the use of get()
in dict?
152. How to check if key exists in dict?
153. What is the difference between pop()
and del
?
pop()
: returns and removesdel
: only removes
154. How to loop through a dict?
155. What is defaultdict?
- Dict with default values from collections.
156. What is Counter?
- Counts occurrences in a collection.
157. How to sort a dict by values?
158. What is OrderedDict
?
- Dict that remembers insertion order (Python 3.7+ dict also does).
159. What does dict.setdefault()
do?
- Returns key if exists, else inserts it with default.
160. How to invert a dictionary?
161. What is map()
?
- Applies a function to each item.
162. What is filter()
?
- Filters items that return True for the function.
163. What is reduce()
used for?
- Applies function cumulatively, e.g., sum, product.
164. What are higher-order functions?
- Functions that take or return functions.
165. What are closures?
- A nested function that remembers values from enclosing scope.
166. What is a lambda function?
- Anonymous, inline function:
167. What is a partial function?
- Function with some arguments fixed using
functools.partial
.
168. What are decorators used for?
- Wrap and modify functions.
169. Can decorators take arguments?
- Yes, via another wrapping function.
170. What is the use of functools.wraps?
- Preserves metadata of the original function.
171. What is currying?
- Converting a function of multiple arguments to one with single arguments.
172. How to memoize functions?
- Using
functools.lru_cache
.
173. How to define a custom decorator?
174. Can a function return another function?
- Yes. Functions are first-class citizens.
175. What is recursion limit in Python?
- Default is 1000, changeable with
sys.setrecursionlimit()
.
176. What is tail recursion?
- A recursion where recursive call is the last operation.
177. Does Python support tail call optimization?
- No, to keep stack traces.
178. What are pure functions?
- Functions without side effects.
179. What are impure functions?
- Functions with side effects (e.g., I/O).
180. What is the difference between yield and return?
yield
: pauses functionreturn
: ends function
181. What is an iterator?
- An object with
__iter__()
and__next__()
.
182.How to make a class iterable?
- Define
__iter__()
and__next__()
.
183. How to get an iterator from a list?
184. What is StopIteration?
- Signals the end of iteration.
185. What is a generator function?
- A function that uses yield to return values one at a time.
186. How to create a generator expression?
187. What is the difference between generator and list comprehension?
Generator
: lazy, memory-efficientList comprehension
: eager, uses memory
188. What is next()
used for?
- Fetches the next value from iterator.
189. How to use send()
in a generator?
- Sends a value into generator after yielding.
190. What is itertools?
- A module with efficient looping utilities.
191. Name some itertools functions.
count()
,cycle()
,repeat()
,product()
,combinations()
192. What is the difference between range()
and xrange()
?
xrange()
exists in Python 2 only.range()
in Python 3 is a generator-like object.
193. What is lazy evaluation?
- Delaying computation until needed (e.g., generators).
194. What is a coroutine?
- A generator that can accept values with
send()
.
195. What is async/await in Python?
- Used for asynchronous programming.
196. What is asyncio?
- A library for writing async code.
197. Can generators be recursive?
- Yes, but use yield from.
198. What does yield from do?
- Delegates to another generator.
199. What happens if you call next()
on a generator that’s done?
- Raises StopIteration.
200. How to check if an object is iterable?
from collections.abc import Iterable isinstance(obj, Iterable)
201. What is unit testing?
- Testing individual parts (units) of code.
202. What module is used for unit testing?
unittest
203. How do you write a test case?
204. What is an assertion?
- A check if a condition is true in a test.
205. Common unittest methods?
assertEqual(a, b)
assertTrue(x)
assertRaises(Error)
206. What is mocking in testing?
- Replacing parts of system with mock objects.
207. How to use pytest?
- Install with pip install pytest, run tests with pytest.
208. How to skip a test?
- Use
@unittest.skip("reason")
.
209. How to group tests?
- Use test classes or test suites.
210. What’s the difference between assert
and assertEqual
?
assert
is Python built-in;assertEqual
is part of unittest.
211. What is TDD (Test Driven Development)?
- Writing tests before the code implementation.
212. How do you test exceptions in unittest?
- Using
assertRaises
.
213. What is nose
or tox
?
- Test runners and automation tools for Python.
214. How to test code coverage?
- Use
coverage.py
.
215. How to debug in Python?
- Use
pdb
, breakpoints, or IDE tools.
216. What is a breakpoint?
- A pause point in code execution for debugging.
217. How to start a debug session?
- Insert
breakpoint()
or usepdb.set_trace()
.
218. How to step through code?
- In
pdb:
n:
nexts:
step intoc:
continue
219. How to print stack trace?
- Use
traceback.print_exc()
.
220. What is assertLogs()
in unittest?
- Tests log output.
221. How to connect to a database in Python?
- Using libraries like
sqlite3
,psycopg2
,SQLAlchemy
.
222. How to connect to SQLite?
223. How to create a table in SQLite?
224. How to insert data into SQLite?
225. How to read data from a table?
226. What is parameterized query?
- SQL query using placeholders to prevent SQL injection.
227. What is ORM?
- Object-Relational Mapper (e.g., SQLAlchemy, Django ORM).
228. How to define a model in SQLAlchemy?
229. How to create a session in SQLAlchemy?
230. How to filter data in SQLAlchemy?
231. How to update data in SQLAlchemy?
232. How to delete a record in SQLAlchemy?
233. What is a transaction?
- Group of operations treated as a single unit.
234. How to use transactions in Python?
- Automatically with context managers or manually with
commit()
androllback()
.
235. How to close a database connection?
236. How to use pandas with SQL?
237. How to write a pandas DataFrame to SQL?
238. What is SQL injection?
- Malicious SQL code via user input; avoid by using parameterized queries.
239. How to handle NULL in Python with SQL?
- Use None in Python; maps to NULL in SQL.
240. What’s the difference between fetchone()
and fetchall()
?
fetchone()
: one recordfetchall()
: all records
241. What is Flask?
- A lightweight WSGI web framework.
242. What is Django?
- A full-featured web framework for building complex sites.
243. How to install Flask?
244. Basic Flask example?
245. What is @app.route()
?
- Defines URL routes.
246. How to pass parameters in URL (Flask)?
247. How to handle forms in Flask?
- Use
request.form
,request.args
248. How to render templates in Flask?
249. How to return JSON in Flask?
250. What is flask run?
- Command to run Flask development server.
251. How to set environment variables in Flask?
252. What is the Django ORM?
- Object-relational mapper to interact with databases.
253. What is a Django model?
- Class that maps to a database table.
254. What is a Django view?
- A function/class that handles a request and returns a response.
255. How to render HTML in Django?
- Use
render(request, 'template.html')
256. What is manage.py
?
- Command-line tool to interact with Django project.
257. What is migrate in Django?
- Apply changes in models to the database schema.
258. What is urls.py
used for?
- Maps URLs to views.
259. What is Django’s settings.py
?
- Holds project configuration.
260. How to create a Django project?
261. How to make HTTP requests in Python?
- Use the requests library.
262. Basic GET request with requests?
263. How to send data with POST?
264. How to send JSON in request?
265. How to get response headers?
266. How to get JSON response?
267. What is an API?
- Application Programming Interface.
268. What is a REST API?
- A web API that follows REST principles.
269. How to handle timeouts in requests?
270. What is status_code
in requests
?
- HTTP response status (e.g., 200, 404)
271. How to handle cookies in requests?
272. How to download a file from URL?
273. What is socket module used for?
- Low-level network communication.
274. How to create a socket server?
275. How to send data via socket?
- Use
send()
andrecv()
methods.
276. What is JSON?
- JavaScript Object Notation, used for data exchange.
277. How to parse JSON in Python?
278. How to convert dict to JSON?
279. What is WebSocket?
- Full-duplex communication channel over a single TCP connection.
280. How to create REST API in Flask?
- Use Flask + Flask-RESTful.
281. How to get current time in Python?
282. How to measure time taken by code?
283. How to run system commands in Python?
284. How to read environment variables?
285. How to use subprocess?
286. How to list files in directory?
287. How to check if a file exists?
288. What is shutil used for?
- File and directory operations.
289. How to copy a file in Python?
290. How to delete a file?
291. What is the use of glob module?
- Pattern matching for filenames.
292. How to create a zip file?
293. How to read a config file?
- Use configparser module.
294. How to serialize data in Python?
- Use pickle, json.
295. What is pickle used for?
- Serialize/deserialize Python objects.
296. How to get memory usage of object?
297. How to handle CLI arguments?
- Use argparse.
298. How to write a CLI program in Python?
- Use argparse or click.
299. How to profile Python code?
- Use cProfile.
300. How to schedule tasks in Python?
- Use schedule, APScheduler, or cron.