└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # 🐍 Python Interview Questions and Answers 2025 2 | 3 | [![GitHub stars](https://img.shields.io/github/stars/nileshhadalgi016/150-python-interview-questions-and-answers?style=social)](https://github.com/nileshhadalgi016/150-python-interview-questions-and-answers) 4 | [![Python](https://img.shields.io/badge/Python-3.11+-blue.svg)](https://www.python.org) 5 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 6 | 7 | A comprehensive collection of Python interview questions and detailed answers for 2025. Perfect for interview preparation and concept review! 🎯 8 | 9 | ## 📚 Table of Contents 10 | 11 | - [Basics and Core Concepts](#basics-and-core-concepts) 12 | - [Control Flow and Looping](#control-flow-and-looping) 13 | - [Functions and Modules](#functions-and-modules) 14 | - [Object-Oriented Programming](#object-oriented-programming) 15 | - [Error Handling and Debugging](#error-handling-and-debugging) 16 | - [File Handling](#file-handling) 17 | - [Data Structures and Algorithms](#data-structures-and-algorithms) 18 | - [Advanced Python Concepts](#advanced-python-concepts) 19 | - [Libraries and Frameworks](#libraries-and-frameworks) 20 | - [Database Connectivity](#database-connectivity) 21 | - [Web Scraping and APIs](#web-scraping-and-apis) 22 | - [Data Science and Machine Learning](#data-science-and-machine-learning) 23 | - [Python 3.11+ Features](#python-311-features) 24 | - [Performance Optimization](#performance-optimization) 25 | - [Security and Best Practices](#security-and-best-practices) 26 | 27 | ## Basics and Core Concepts 28 | 29 | 1. What is Python, and what are its key features? 30 | Python is a high-level, interpreted programming language known for its simplicity and readability. Key features include dynamic typing, object-oriented design, extensive standard libraries, and support for multiple programming paradigms (procedural, object-oriented, functional). Python’s syntax is simple, making it easy for beginners while remaining powerful for advanced users. 31 | 32 | 2. How does Python manage memory? 33 | Python manages memory with a built-in garbage collector, which automatically frees up memory by removing unused or unreachable objects. Memory management is handled through reference counting and the garbage collection mechanism in the gc module, ensuring efficient memory use without requiring manual intervention. 34 | 35 | 3. What are the key differences between Python 2 and Python 3? 36 | Python 3 introduced several improvements and changes over Python 2, including better Unicode support, print() as a function, integer division behavior (/ vs. //), and more consistent syntax. Python 3 is faster and supports modern libraries, while Python 2 is no longer officially supported. 37 | 38 | 4. Explain the difference between a list and a tuple. 39 | Lists are mutable, meaning their elements can be modified, added, or removed after creation. Tuples are immutable, so their content cannot change after creation. Lists are enclosed in square brackets ([]), while tuples use parentheses (()), and tuples often serve as fixed data structures for constant data. 40 | 41 | 5. How does Python handle type conversion? 42 | Python allows implicit type conversion (automatic) where possible, but explicit conversion functions (e.g., int(), float(), str()) are often used for controlled conversions. Type conversion helps align data types during operations or when passing data between functions. 43 | 44 | 6. What is the use of the pass statement? 45 | The pass statement is a placeholder in Python, used when a statement is syntactically required but no action is necessary. For example, it’s commonly used in empty function definitions or loops that will be implemented later, allowing the code to run without errors. 46 | 47 | 7. What is the difference between append() and extend() methods in lists? 48 | append() adds a single item (or an object) to the end of a list, while extend() takes an iterable (e.g., list, tuple) and adds each element to the list individually. append() results in a nested list if used with a list, whereas extend() merges the elements of the given iterable. 49 | 50 | 8. Explain the use of the self keyword in classes. 51 | self is used as the first parameter in instance methods of a class to refer to the instance on which the method is called. It allows access to instance attributes and other methods within the same class, enabling object-specific behavior and data. 52 | 53 | 9. What are Python’s built-in data types? 54 | Python’s built-in data types include: 55 | • Numeric: int, float, complex 56 | • Sequence: str, list, tuple 57 | • Mapping: dict 58 | • Set: set, frozenset 59 | • Boolean: bool 60 | • NoneType: None 61 | 62 | 10. How do you handle exceptions in Python? 63 | Python uses try, except, else, and finally blocks to handle exceptions. Code within the try block is executed, and if an exception occurs, it’s caught by the except block. else runs if no exceptions are raised, and finally runs regardless of exceptions, typically used for cleanup tasks. 64 | 65 | ### Control Flow and Looping 66 | 67 | 11. What is the purpose of if __name__ == "__main__" in Python? 68 | This conditional statement checks whether a Python script is being run directly (as the main program) or being imported as a module in another script. Code within this block will execute only if the script is run directly, allowing you to include test code or script-specific functionality without affecting imports. 69 | 70 | 12. Explain how for and while loops work in Python. 71 | • A for loop iterates over items in a sequence (like a list or a string) or any iterable object. It executes the block of code for each item in the sequence. 72 | • A while loop continues to execute as long as a given condition is True. It checks the condition before each iteration and exits the loop once the condition evaluates to False. 73 | 74 | 13. What is a generator, and how do you use it? 75 | A generator is a special type of iterator that yields values one at a time and maintains state between iterations, allowing you to iterate over potentially large sequences without loading everything into memory. You create a generator using a function that contains the yield statement. For example: 76 | 77 | ``` 78 | def my_generator(): 79 | yield 1 80 | yield 2 81 | 82 | ``` 83 | 14. What are list comprehensions in Python? 84 | List comprehensions provide a concise way to create lists. They consist of an expression followed by a for clause, and can include an optional if clause. For example: 85 | ``` 86 | squares = [x**2 for x in range(10)] 87 | ``` 88 | 89 | 90 | 15. How do you break out of a loop in Python? 91 | You can break out of a loop using the break statement. When break is encountered, the loop terminates immediately, and control passes to the first statement following the loop. For example: 92 | ``` 93 | for x in range(10): 94 | if x == 5: 95 | break 96 | 97 | ``` 98 | 16. What are lambda functions, and when would you use them? 99 | Lambda functions are anonymous functions defined with the lambda keyword. They can take any number of arguments but have only one expression. They’re often used for short, throwaway functions, especially as arguments to higher-order functions like map(), filter(), or sorted(). For example: 100 | ``` 101 | square = lambda x: x**2 102 | 103 | ``` 104 | 17. How does Python’s range() function work? 105 | The range() function generates a sequence of numbers, commonly used in loops. It can take one to three arguments: start, stop, and step. It produces numbers from start to stop (exclusive) with the specified step. For example: 106 | ``` 107 | for i in range(0, 10, 2): # Generates 0, 2, 4, 6, 8 108 | ``` 109 | 110 | 111 | 18. What is the difference between return and yield? 112 | return exits a function and sends a value back to the caller, terminating the function’s execution. In contrast, yield pauses the function, allowing it to produce a value and maintain its state, enabling the function to be resumed later. Functions that use yield are called generators. 113 | 114 | 19. Explain how map(), filter(), and reduce() work. 115 | • map() applies a function to every item in an iterable and returns a map object (which can be converted to a list). For example: 116 | 117 | ``` 118 | squares = map(lambda x: x**2, [1, 2, 3]) 119 | ``` 120 | 121 | • filter() filters items in an iterable based on a function that returns True or False. It returns a filter object. For example: 122 | ``` 123 | evens = filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) 124 | ``` 125 | 126 | • reduce() from the functools module applies a function cumulatively to the items of an iterable, reducing it to a single value. For example: 127 | ``` 128 | from functools import reduce 129 | product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) # Returns 24 130 | ``` 131 | 132 | 20. What is a continue statement, and when would you use it? 133 | The continue statement is used within loops to skip the current iteration and proceed to the next iteration. It is useful when you want to skip certain conditions without breaking the entire loop. For example: 134 | ``` 135 | for x in range(10): 136 | if x % 2 == 0: 137 | continue # Skip even numbers 138 | ``` 139 | 140 | ### Functions and Modules 141 | 142 | 21. What is a Python module, and how do you create one? 143 | 22. How do you import modules in Python? 144 | 23. What are decorators in Python? 145 | 24. What is the purpose of *args and **kwargs? 146 | 25. Explain global, local, and nonlocal variables in Python. 147 | 26. How does Python handle default argument values in functions? 148 | 27. Explain closures in Python. 149 | 28. How do you define a function in Python? 150 | 29. What is recursion? Give an example. 151 | 30. Explain function overloading and method overloading in Python. 152 | 153 | ### Object-Oriented Programming (OOP) 154 | 155 | 31. What are classes and objects in Python? 156 | 32. Explain inheritance in Python. 157 | 33. What is polymorphism, and how is it achieved in Python? 158 | 34. What is an abstract class? 159 | 35. Explain encapsulation with an example. 160 | 36. What are magic methods (dunder methods) in Python? 161 | 37. How does multiple inheritance work in Python? 162 | 38. What is the difference between class and instance variables? 163 | 39. Explain the concept of method overriding in Python. 164 | 40. What is a metaclass, and why would you use it? 165 | 166 | ### Error Handling and Debugging 167 | 168 | 41. How do you handle exceptions in Python? 169 | 42. What are the built-in exceptions in Python? 170 | 43. Explain the use of try, except, else, and finally. 171 | 44. What is raise used for in Python? 172 | 45. How can you log errors in Python? 173 | 46. Explain the purpose of assert in Python. 174 | 47. How can you debug code in Python? 175 | 48. What is the difference between try-except and try-finally? 176 | 49. How do you handle multiple exceptions? 177 | 50. What is traceback, and how can you read it? 178 | 179 | ### File Handling 180 | 181 | 51. How do you open and close files in Python? 182 | 52. Explain the difference between read() and readlines(). 183 | 53. How do you write to a file in Python? 184 | 54. What are context managers, and how are they used in file handling? 185 | 55. How do you delete a file in Python? 186 | 56. Explain the purpose of with open() in file handling. 187 | 57. How do you check if a file exists in Python? 188 | 58. What is the seek() method used for? 189 | 59. How do you handle file encoding? 190 | 60. Explain the difference between binary and text files. 191 | 192 | ### Data Structures and Algorithms 193 | 194 | 61. Explain how a list works in Python. 195 | 62. How is a dictionary different from a list? 196 | 63. What are sets in Python, and when would you use them? 197 | 64. What is the difference between set() and frozenset()? 198 | 65. How can you sort a list in Python? 199 | 66. Explain heaps and when to use them. 200 | 67. What is a stack, and how is it implemented in Python? 201 | 68. Explain the concept of queues in Python. 202 | 69. How do you remove duplicates from a list? 203 | 70. What are defaultdict and OrderedDict in collections? 204 | 205 | ### Advanced Python Concepts 206 | 207 | 71. What is a virtual environment, and why is it important? 208 | 72. Explain memory management in Python. 209 | 73. What is GIL (Global Interpreter Lock)? 210 | 74. How does Python handle multithreading? 211 | 75. What is a coroutine? 212 | 76. Explain the use of async and await. 213 | 77. What are iterators and iterables? 214 | 78. How does garbage collection work in Python? 215 | 79. What is the difference between deep copy and shallow copy? 216 | 80. Explain the concept of monkey patching. 217 | 218 | ### Libraries and Frameworks 219 | 220 | 81. What is Django, and what is it used for? 221 | 82. Explain Flask and how it is different from Django. 222 | 83. How does NumPy handle large datasets? 223 | 84. What is the purpose of the pandas library? 224 | 85. What is the use of the requests library in Python? 225 | 86. Explain Matplotlib and its applications. 226 | 87. What is TensorFlow, and how does it relate to Python? 227 | 88. How does Python’s BeautifulSoup library work? 228 | 89. What are the features of Scikit-Learn? 229 | 90. Explain the purpose of the PyTorch library. 230 | 231 | ### Database Connectivity 232 | 233 | 91. How do you connect to a database in Python? 234 | 92. What is the use of SQLite in Python? 235 | 93. Explain SQLAlchemy and its benefits. 236 | 94. How do you execute SQL queries in Python? 237 | 95. What is a cursor in Python DB connectivity? 238 | 96. How can you handle transactions in Python? 239 | 97. How do you use MySQL with Python? 240 | 98. Explain the concept of ORM. 241 | 99. How can you prevent SQL injection in Python? 242 | 100. What is PyMongo, and how does it work? 243 | 244 | ### Web Scraping and APIs 245 | 246 | 101. How does web scraping work in Python? 247 | 102. Explain the use of Selenium. 248 | 103. What are APIs, and how do you use them in Python? 249 | 104. How do you handle JSON data? 250 | 105. What is the difference between REST and SOAP APIs? 251 | 106. How do you parse XML in Python? 252 | 107. Explain the use of the requests module for APIs. 253 | 108. How do you handle rate limits while scraping? 254 | 109. What is XPath, and how is it used? 255 | 110. How can you create a simple web scraper in Python? 256 | 257 | ### Data Science and Machine Learning 258 | 259 | 111. How is Python used in data science? 260 | 112. Explain data preprocessing with Python. 261 | 113. What is the purpose of the Keras library? 262 | 114. How does feature engineering work in Python? 263 | 115. Explain the concept of clustering in ML. 264 | 116. What are Jupyter Notebooks? 265 | 117. How does Python handle big data? 266 | 118. What are the features of SciPy? 267 | 119. Explain linear regression with Python. 268 | 120. How do you evaluate ML models in Python? 269 | 270 | ### Python 3.11+ Specifics (Newer Updates) 271 | 272 | 121. What are structural pattern matching features? 273 | 122. Explain the performance improvements in Python 3.11. 274 | 123. What is the match case used for? 275 | 124. How has error handling improved in newer versions? 276 | 125. Explain the improvements in async IO. 277 | 126. What’s new in data classes in Python 3.11? 278 | 127. What are typing improvements in Python 3.11? 279 | 128. How has the standard library evolved? 280 | 129. What are the new string interpolation options? 281 | 130. How does exception group work in Python 3.11? 282 | 283 | ### Advanced Concepts and Performance Optimization 284 | 285 | 131. How can you improve the performance of a Python application? 286 | 132. What are asyncio tasks and events? 287 | 133. Explain the difference between concurrency and parallelism. 288 | 134. What are Python’s profiling tools (e.g., cProfile, line_profiler)? 289 | 135. How do you manage dependencies in Python? 290 | 136. What is the use of the functools module? 291 | 137. How can you measure memory usage in Python? 292 | 138. What is weakref in Python, and when would you use it? 293 | 139. Explain the mmap module and its applications. 294 | 140. How do you handle large JSON files efficiently? 295 | 296 | ### Security and Best Practices 297 | 298 | 141. What are some best practices for securing Python applications? 299 | 142. How do you securely handle sensitive data in Python? 300 | 143. What are common Python security vulnerabilities? 301 | 144. Explain the use of bcrypt and hashlib for secure password handling. 302 | 145. What is code injection, and how can you prevent it? 303 | 146. What are the benefits of code linting, and which tools are used in Python? 304 | 147. How can you prevent command injection in Python? 305 | 148. Explain the concept of “sandboxing” and when it’s used. 306 | 149. What are type annotations, and how do they improve code quality? 307 | 150. How can you manage environment variables securely in Python? 308 | 309 | 310 | 311 | ## 🤝 Contributing 312 | 313 | Feel free to contribute to this repository by: 314 | 1. Forking the project 315 | 2. Creating your feature branch 316 | 3. Committing your changes 317 | 4. Pushing to the branch 318 | 5. Opening a Pull Request 319 | 320 | ## 📝 License 321 | 322 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. 323 | 324 | ## ⭐ Star this repository 325 | 326 | If you find this helpful, please consider giving it a star! It helps others discover this resource. 327 | 328 | --- 329 | Made with ❤️ by Nilesh Hadalgi | Techie Programmer 330 | 331 | 332 | --------------------------------------------------------------------------------