Top 100 Python Interview Questions and Answers
1. What is Python?
Answer: Python is a high-level, interpreted programming language known for its readability and
versatility.
2. List some features of Python.
Answer: Easy to learn, interpreted, dynamically typed, object-oriented, and has a large standard
library.
3. What are the key differences between Python 2 and Python 3?
Answer: Python 3 uses print() function, handles strings differently, and has better Unicode support.
4. What are Python's data types?
Answer: int, float, bool, str, list, tuple, set, dict, complex, and NoneType.
5. What is the difference between list and tuple?
Answer: Lists are mutable, while tuples are immutable.
6. What is the use of a dictionary in Python?
Answer: It stores data in key-value pairs.
7. What are sets in Python?
Answer: Sets are unordered collections of unique elements.
8. What is slicing in Python?
Answer: It is a way to retrieve a portion of a sequence using [start:stop:step].
9. How does Python handle memory management?
Answer: Through reference counting and garbage collection.
10. What is the difference between deep copy and shallow copy?
Answer: Shallow copy copies references, deep copy copies the objects recursively.
11. What are Python modules and packages?
Answer: Modules are single Python files, packages are collections of modules with __init__.py.
12. What is PEP 8?
Answer: PEP 8 is a style guide for Python code.
13. What is indentation in Python?
Answer: It defines the blocks of code; proper indentation is mandatory.
14. What is the difference between is and ==?
Answer: `is` checks identity, `==` checks equality.
15. How do you comment in Python?
Answer: Using `#` for single-line, and triple quotes for multi-line comments.
16. What is the use of pass in Python?
Answer: `pass` is a null operation used as a placeholder.
17. What are *args and **kwargs?
Answer: *args is for variable-length arguments, **kwargs is for keyworded variable-length
arguments.
18. What is a lambda function?
Answer: A small anonymous function using the `lambda` keyword.
19. What is a docstring?
Answer: A string used to document a specific segment of code.
20. How to handle exceptions in Python?
Answer: Using try-except-finally blocks.
21. What are list comprehensions?
Answer: A concise way to create lists using a single line of code.
22. What is a generator?
Answer: A function that yields values one at a time using `yield`.
23. What is the difference between yield and return?
Answer: `yield` returns a generator object, `return` exits a function with a value.
24. What is a decorator?
Answer: A function that modifies another function's behavior.
25. What is a closure?
Answer: A function with access to variables in its lexical scope, even when called outside that
scope.
26. Explain Python namespaces.
Answer: Namespaces are containers for mapping names to objects.
27. What is scope in Python?
Answer: The region where a variable is recognized (local, enclosing, global, built-in).
28. What is the global keyword?
Answer: Used to modify a global variable inside a function.
29. What is the nonlocal keyword?
Answer: Used to modify a variable in the outer (non-global) scope.
30. How does Python implement multithreading?
Answer: Using the threading module, although GIL limits true parallelism.
31. What is the GIL?
Answer: Global Interpreter Lock, allowing only one thread at a time in CPython.
32. What are Python's built-in functions?
Answer: Examples include len(), type(), print(), id(), sum(), etc.
33. What is the difference between append() and extend()?
Answer: append() adds an element, extend() adds multiple elements.
34. How do you merge two dictionaries in Python?
Answer: Using the update() method or `{**d1, **d2}` in Python 3.5+.
35. What is map() function?
Answer: Applies a function to all items in an iterable.
36. What is filter() function?
Answer: Filters elements for which the function returns True.
37. What is reduce() function?
Answer: Applies a rolling computation to a sequence (from functools).
38. What is zip() function?
Answer: Combines multiple iterables element-wise.
39. What is enumerate()?
Answer: Returns an iterable with index-value pairs.
40. What are magic methods?
Answer: Special methods like __init__, __str__, __len__, etc.
41. What is __init__?
Answer: A constructor method called when an object is created.
42. What is __str__?
Answer: Returns the string representation of the object.
43. Explain inheritance in Python.
Answer: A class can inherit attributes and methods from another class.
44. What is multiple inheritance?
Answer: A class can inherit from more than one parent class.
45. What is method overriding?
Answer: Redefining a parent class method in a child class.
46. What is super()?
Answer: Used to call methods of a parent class.
47. What is isinstance()?
Answer: Checks if an object is an instance of a class or tuple of classes.
48. What is hasattr() and getattr()?
Answer: hasattr checks for attribute existence, getattr retrieves it.
49. What is the difference between classmethod and staticmethod?
Answer: classmethod takes cls, staticmethod takes no default argument.
50. What is monkey patching?
Answer: Changing code at runtime dynamically.
51. What is the difference between == and is?
Answer: `==` compares values, `is` compares identities.
52. What is the difference between repr() and str()?
Answer: repr is for developers, str is for users.
53. What are Python iterators?
Answer: Objects representing a stream of data with __next__ method.
54. What is a context manager?
Answer: Used with `with` statement to manage resources.
55. What are the different file modes in Python?
Answer: 'r', 'w', 'a', 'r+', 'b', etc.
56. What is pickling in Python?
Answer: Serializing objects using the pickle module.
57. What are Python libraries?
Answer: Reusable collections of functions and classes.
58. What is virtualenv?
Answer: Tool to create isolated Python environments.
59. What is pip?
Answer: Python's package installer.
60. What is the difference between @staticmethod and @classmethod?
Answer: staticmethod doesn't take any implicit arguments; classmethod takes the class.
61. What are metaclasses in Python?
Answer: A class of a class; controls class creation.
62. What is duck typing?
Answer: Object's behavior is more important than its type.
63. What is the use of __slots__?
Answer: Restricts the creation of instance attributes, saves memory.
64. What is the purpose of the assert statement?
Answer: Used to test if a condition is true.
65. How can you handle memory leaks in Python?
Answer: Using weak references and careful resource management.
66. What is asyncio in Python?
Answer: Library for writing asynchronous code using async/await syntax.
67. What is the purpose of the 'with' statement?
Answer: To wrap the execution of a block with methods defined by a context manager.
68. What are coroutines?
Answer: Special generators that can consume values and yield results.
69. What is a memoryview?
Answer: A memory-efficient view of large binary data.
70. How do you measure performance in Python?
Answer: Using timeit or profiling tools like cProfile.
71. What is the difference between static and dynamic typing?
Answer: Static types are known at compile time; dynamic types at runtime.
72. What is unittest in Python?
Answer: A testing framework for writing and running tests.
73. What are Python's popular frameworks?
Answer: Django, Flask, FastAPI for web; Pandas, NumPy for data.
74. What is the use of the re module?
Answer: Regular expressions for pattern matching.
75. How do you handle JSON in Python?
Answer: Using the json module for serialization/deserialization.
76. What are Python's data science libraries?
Answer: NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow.
77. How do you create a REST API in Python?
Answer: Using Flask or FastAPI frameworks.
78. What is the difference between compile time and runtime?
Answer: Compile time is before execution; runtime is during execution.
79. What are Python descriptors?
Answer: Objects that manage attribute access using __get__, __set__, and __delete__.
80. What is the difference between module and package?
Answer: Module is a .py file; package is a folder with __init__.py.
81. What is the difference between CPython and Jython?
Answer: CPython is default Python in C; Jython runs on Java platform.
82. How does Python manage memory?
Answer: Using private heap space and garbage collection.
83. What is the __main__ block?
Answer: Used to execute some code only when the file is run directly.
84. What is the walrus operator?
Answer: The := operator assigns values as part of an expression.
85. What is the difference between async and threading?
Answer: async is cooperative multitasking; threading is pre-emptive.
86. How to handle missing values in Python?
Answer: Using pandas functions like fillna() or dropna().
87. What are f-strings?
Answer: Formatted string literals introduced in Python 3.6.
88. How do you connect to a database in Python?
Answer: Using libraries like sqlite3, SQLAlchemy, or psycopg2.
89. What is the difference between int() and float()?
Answer: int() converts to integer, float() to floating-point.
90. How to handle command-line arguments?
Answer: Using sys.argv or argparse module.
91. What is multithreading vs multiprocessing?
Answer: Multithreading shares memory; multiprocessing uses separate memory space.
92. What are weak references?
Answer: Allow access to an object without preventing its garbage collection.
93. What is the use of the traceback module?
Answer: Provides error message and stack trace information.
94. What are type hints?
Answer: Hints about variable types introduced in Python 3.5+.
95. How do you ensure code quality?
Answer: Using tools like pylint, flake8, and writing unit tests.
96. What is the use of the dataclasses module?
Answer: Provides a decorator and functions for automatically adding special methods to classes.
97. How do you build and install a Python package?
Answer: Using setuptools and pip for distribution.