Skip to content
python interview questions

150 Python Interview Questions (From Basic to Advanced)

Python has become one of the most popular programming languages due to its simplicity, versatility, and robust community support. Whether you’re a beginner looking to start your coding journey or an experienced developer preparing for a technical interview, understanding Python’s core concepts and advanced features is crucial.

This blog provides a comprehensive list of Python interview questions, categorized into basic, medium, and advanced levels, along with their answers. These questions are designed to help you reinforce your knowledge, prepare for interviews, and stay ahead in your Python programming career.

Let’s dive into the essentials and nuances of Python with these 150 interview questions and answers.

Basic Python Interview Questions

1. What is Python?

Python is a high-level, interpreted, and general-purpose programming language known for its readability and simplicity.

2. How do you create a variable in Python?

Variables are created by assigning a value using the = operator, e.g., x = 10.

3. What is the difference between a list and a tuple in Python?

Lists are mutable, meaning they can be changed after creation, while tuples are immutable.

4. How do you write a comment in Python?

Comments are written using the # symbol, e.g., # This is a comment.

5. What are Python’s data types?

Common data types include int, float, str, list, tuple, dict, and set.

6. How do you create a list in Python?

Lists are created using square brackets, e.g., my_list = [1, 2, 3].

7. How do you create a dictionary in Python?

Dictionaries are created using curly braces, e.g., my_dict = {'key': 'value'}.

8. What is a function in Python?

A function is a block of reusable code that performs a specific task, defined using the def keyword.

9. How do you call a function in Python?

Functions are called using their name followed by parentheses, e.g., my_function().

10. What is a loop in Python?

Loops are used to repeat a block of code multiple times, with for and while being the two main types of loops.

11. How do you create a for loop in Python?

A for loop is created using the for keyword, e.g., for i in range(5):.

12. How do you create a while loop in Python?

A while loop is created using the while keyword, e.g., while condition:.

13. What is an if statement in Python?

An if statement is used to execute code based on a condition, e.g., if condition:.

14. How do you check for equality in Python?

Equality is checked using the == operator, e.g., if x == y:.

15. How do you concatenate strings in Python?

Strings are concatenated using the + operator, e.g., str1 + str2.

16. What is a module in Python?

A module is a file containing Python code that can be imported and used in other Python files.

17. How do you import a module in Python?

Modules are imported using the import keyword, e.g., import math.

18. What is the use of the len() function?

The len() function returns the length of an object, such as a list or a string.

19. How do you handle exceptions in Python?

Exceptions are handled using try and except blocks, e.g., try: ... except: ....

20. What is a list comprehension in Python?

A list comprehension is a concise way to create lists using a single line of code, e.g., [x for x in range(5)].

21. How do you create a tuple in Python?

Tuples are created using parentheses, e.g., my_tuple = (1, 2, 3).

22. How do you access elements in a list?

Elements in a list are accessed using square brackets with the index, e.g., my_list[0].

23. What is slicing in Python?

Slicing is a way to get a subset of elements from a list or string using the colon : operator.

24. How do you create a set in Python?

Sets are created using curly braces or the set() function, e.g., my_set = {1, 2, 3}.

25. How do you add an element to a list?

Elements are added to a list using the append() method, e.g., my_list.append(4).

26. How do you remove an element from a list?

Elements are removed from a list using the remove() method, e.g., my_list.remove(2).

27. How do you check if an element is in a list?

Use the in keyword, e.g., if 2 in my_list:.

28. What is the difference between == and is?

== checks for equality of values, while is checks for identity (if they are the same object in memory).

29. How do you convert a string to an integer in Python?

Use the int() function, e.g., int("123").

30. How do you convert an integer to a string in Python?

Use the str() function, e.g., str(123).

31. What is a lambda function in Python?

A lambda function is an anonymous function defined using the lambda keyword.

32. How do you create a class in Python?

Classes are created using the class keyword, e.g., class MyClass:.

33. What is an object in Python?

An object is an instance of a class, containing data and methods.

34. How do you create an object in Python?

Objects are created by calling the class, e.g., obj = MyClass().

35. What is inheritance in Python?

Inheritance is a way to create a new class from an existing class, inheriting its attributes and methods.

36. How do you create a subclass in Python?

Subclasses are created by specifying the parent class in parentheses, e.g., class SubClass(ParentClass):.

37. What is polymorphism in Python?

Polymorphism allows methods to be used interchangeably based on the object, even if they belong to different classes.

38. What is encapsulation in Python?

Encapsulation restricts direct access to an object’s data, using methods to interact with it.

39. What is the self keyword in Python?

self refers to the instance of the class and is used to access variables and methods within the class.

40. How do you create a method in a class?

Methods are defined using the def keyword within a class, e.g., def my_method(self):.

41. How do you open a file in Python?

Files are opened using the open() function, e.g., file = open('filename.txt', 'r').

42. How do you read a file in Python?

Files are read using the read() method, e.g., content = file.read().

43. How do you write to a file in Python?

Files are written to using the write() method, e.g., file.write('Hello, World!').

44. How do you close a file in Python?

Files are closed using the close() method, e.g., file.close().

45. What is the purpose of the with statement?

The with statement is used to handle file operations, ensuring the file is properly closed, e.g., with open('file.txt', 'r') as file:.

46. How do you check the data type of a variable?

The data type is checked using the type() function, e.g., type(variable).

47. What is the purpose of the pass statement?

The pass statement is a placeholder that does nothing, often used in empty functions or loops.

48. How do you generate random numbers in Python?

Random numbers are generated using the random module, e.g., import random; random.randint(1, 10).

49. What is the difference between range() and xrange()?

In Python 3, xrange() is not available, and range() returns an iterator instead of a list.

50. How do you create a virtual environment in Python?

Virtual environments are created using venv, e.g., python -m venv myenv.

Medium Python Interview Questions

51. What is the purpose of the __init__ method in Python?

The __init__ method initializes an object’s attributes and is called automatically when a new instance is created.

52. How do you implement a stack in Python?

A stack can be implemented using a list with append() and pop() methods to push and pop elements.

53. What are decorators in Python?

Decorators are functions that modify the behavior of other functions or methods, using the @decorator syntax.

54. How do you implement a queue in Python?

A queue can be implemented using the collections.deque class with append() and popleft() methods.

55. What are list comprehensions and how are they used?

List comprehensions are a concise way to create lists, e.g., [x**2 for x in range(10)].

56. What is the purpose of the yield keyword in Python?

The yield keyword is used to create generators, which return an iterator and allow iteration over a sequence of values.

57. How do you handle multiple exceptions in a single block?

Multiple exceptions are handled using a tuple, e.g., except (TypeError, ValueError):.

58. What is the difference between __str__ and __repr__ methods?

__str__ is used for creating output for end-users, while __repr__ is used for debugging and development.

59. How do you merge two dictionaries in Python?

Dictionaries can be merged using the update() method or {**dict1, **dict2} in Python 3.5+.

60. What are the built-in data structures in Python?

Built-in data structures include lists, tuples, sets, and dictionaries.

61. How do you sort a list in Python?

Lists are sorted using the sort() method or the sorted() function.

62. What is the zip() function used for?

The zip() function combines elements from multiple iterables into tuples.

63. What are the differences between Python 2 and Python 3?

Key differences include print function syntax, integer division, Unicode handling, and the xrange() function.

64. How do you perform matrix multiplication in Python?

Matrix multiplication can be performed using nested loops, list comprehensions, or libraries like NumPy.

65. How do you remove duplicates from a list?

Duplicates are removed using a set or list comprehension with a condition.

66. How do you find the intersection of two lists?

The intersection is found using set operations, e.g., set(list1) & set(list2).

67. What are Python’s built-in functions?

Some built-in functions include len(), max(), min(), sum(), and sorted().

68. How do you implement a linked list in Python?

A linked list can be implemented using classes with Node and LinkedList structures.

69. What are metaclasses in Python?

Metaclasses are classes of classes that define how classes behave.

70. How do you reverse a string in Python?

Strings are reversed using slicing, e.g., my_string[::-1].

71. What are Python’s file handling modes?

File handling modes include r (read), w (write), a (append), and b (binary).

72. How do you create a generator in Python?

Generators are created using functions with the yield keyword.

73. What is the difference between deepcopy and copy?

copy creates a shallow copy, while deepcopy creates a deep copy, including nested objects.

74. How do you use the itertools module?

The itertools module provides functions for creating iterators for efficient looping.

75. What are the different types of inheritance in Python?

Types of inheritance include single, multiple, multilevel, hierarchical, and hybrid inheritance.

76. How do you implement method overloading in Python?

Method overloading can be achieved using default arguments or variable-length arguments.

77. What are the benefits of using NumPy arrays over Python lists?

NumPy arrays provide efficient storage, faster operations, and support for multi-dimensional data.

78. How do you find the maximum and minimum elements in a list?

Use the max() and min() functions to find the maximum and minimum elements.

79. What are Python’s special methods?

Special methods (or magic methods) include __init__, __str__, __repr__, __len__, etc.

80. How do you measure the performance of a Python script?

Performance is measured using modules like timeit or cProfile.

81. What is the self parameter in a class method?

self refers to the instance of the class and is used to access its attributes and methods.

82. How do you handle circular imports in Python?

Circular imports are handled by restructuring the code or using import statements within functions.

83. What is the map() function used for?

The map() function applies a given function to all items in an iterable.

84. How do you implement a binary search algorithm in Python?

Binary search is implemented using a loop or recursion, with O(log n) complexity.

85. What is the difference between filter() and map()?

filter() filters elements based on a condition, while map() applies a function to all elements.

86. How do you handle date and time in Python?

Date and time are handled using the datetime module.

87. What is the collections module?

The collections module provides specialized data structures like deque, Counter, OrderedDict, etc.

88. How do you use the reduce() function?

The reduce() function applies a function cumulatively to items of an iterable, reducing it to a single value.

89. What are the different ways to format strings in Python?

Strings are formatted using % operator, str.format(), and f-strings (formatted string literals).

90. How do you create and use a context manager?

Context managers are created using with statement and __enter__ and __exit__ methods.

91. How do you find the GCD of two numbers in Python?

GCD is found using math.gcd(a, b) function.

92. What are Python’s try, except, else, and finally blocks?

They are used for handling exceptions: try for the code to test, except for handling exceptions, else for code that runs if no exceptions occur, and finally for code that runs regardless of exceptions.

93. How do you implement a simple web server in Python?

A simple web server can be implemented using the http.server module.

94. How do you sort a dictionary by its values?

Dictionaries are sorted by values using sorted() with a key argument, e.g., sorted(dict.items(), key=lambda item: item[1]).

95. What is a namespace in Python?

A namespace is a container that holds names (variables) and their corresponding objects.

96. How do you create a package in Python?

Packages are created by organizing modules into directories with an __init__.py file.

97. What is a set comprehension?

A set comprehension is a concise way to create sets, e.g., {x for x in range(10)}.

98. How do you create a thread in Python?

Threads are created using the threading module, e.g., threading.Thread(target=func).

99. What is the difference between append() and extend()?

append() adds a single element to the list, while extend() adds multiple elements.

100. How do you find the common elements in two lists?

Common elements are found using set intersection, e.g., set(list1) & set(list2).

Advanced Python Interview Questions

101. What is the Global Interpreter Lock (GIL)?

The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes simultaneously.

102. How do you optimize the performance of a Python program?

Performance is optimized using profiling, efficient algorithms, minimizing global variable usage, and leveraging libraries like NumPy.

103. What are Python’s memory management techniques?

Python uses reference counting and garbage collection for memory management.

104. How do you use decorators to implement memoization?

Memoization is implemented using decorators to cache results of expensive function calls.

105. What is the abc module used for?

The abc module provides tools for defining abstract base classes.

106. How do you create a metaclass in Python?

Metaclasses are created by inheriting from type and defining the __new__ and __init__ methods.

107. What is the purpose of super() in Python?

super() is used to call a method from the parent class.

108. How do you implement a singleton pattern in Python?

A singleton pattern is implemented by overriding the __new__ method to ensure only one instance exists.

109. What is the functools module used for?

The functools module provides higher-order functions for working with other functions, such as reduce, partial, and lru_cache.

110. How do you handle missing keys in a dictionary?

Missing keys are handled using the get() method or collections.defaultdict.

111. How do you implement a priority queue in Python?

A priority queue is implemented using the heapq module.

112. What is a context manager and how is it implemented?

Context managers are implemented using the with statement and __enter__ and __exit__ methods.

113. What are coroutines in Python?

Coroutines are generalizations of subroutines, allowing execution to be paused and resumed, typically using async and await keywords.

114. How do you use the multiprocessing module?

The multiprocessing module is used to create and manage separate processes for parallel execution.

115. What is the __slots__ attribute?

The __slots__ attribute is used to declare data members and save memory by preventing the creation of __dict__.

116. How do you create a custom exception?

Custom exceptions are created by inheriting from the Exception

class.

117. What is the difference between synchronous and asynchronous programming?

Synchronous programming waits for each operation to complete before proceeding, while asynchronous programming allows execution to continue without waiting for operations to finish.

118. How do you use the selectors module?

The selectors module is used for high-level I/O multiplexing, allowing efficient handling of multiple I/O operations.

119. What are the benefits of using asyncio?

asyncio provides support for asynchronous I/O, allowing the development of concurrent code using async and await.

120. How do you implement a binary tree in Python?

A binary tree is implemented using classes with Node and BinaryTree structures.

121. How do you use the mock module?

The mock module is used for testing by creating mock objects and assertions.

122. What is the purpose of the inspect module?

The inspect module provides tools for introspecting live objects, such as functions, classes, and modules.

123. How do you create a descriptor in Python?

Descriptors are created by defining __get__, __set__, and __delete__ methods in a class.

124. What are metaclasses and how are they used?

Metaclasses are classes of classes that define how classes behave, used to modify class creation.

125. How do you use the ctypes module?

The ctypes module provides C-compatible data types and allows calling functions in DLLs or shared libraries.

126. How do you implement a thread pool in Python?

A thread pool is implemented using the concurrent.futures.ThreadPoolExecutor class.

127. What are context variables?

Context variables are used to manage state in asynchronous code, maintaining separate contexts for each task.

128. How do you use the dataclasses module?

The dataclasses module is used to create classes for storing data with less boilerplate code.

129. What is the pathlib module?

The pathlib module provides an object-oriented approach to handling filesystem paths.

130. How do you create and use a named tuple?

Named tuples are created using the collections.namedtuple function, providing tuple-like objects with named fields.

131. What is monkey patching?

Monkey patching refers to modifying or extending code at runtime.

132. How do you use the subprocess module?

The subprocess module is used to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

133. What is the traceback module used for?

The traceback module provides utilities for extracting, formatting, and printing stack traces of exceptions.

134. How do you create a RESTful API in Python?

A RESTful API is created using frameworks like Flask or Django, defining routes and handling HTTP requests.

135. How do you use the weakref module?

The weakref module provides tools for creating weak references to objects, allowing them to be garbage-collected.

136. What is the pandas library used for?

The pandas library is used for data manipulation and analysis, providing data structures like DataFrame and Series.

137. How do you use the logging module?

The logging module provides a flexible framework for emitting log messages from Python programs.

138. What are Python’s memoryview objects?

Memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.

139. How do you handle concurrent execution in Python?

Concurrent execution is handled using threads, processes, and asynchronous programming.

140. What is the sched module used for?

The sched module provides a general-purpose event scheduler for executing tasks at specific times.

141. How do you use the timeit module?

The timeit module is used to measure the execution time of small code snippets.

142. How do you handle binary data in Python?

Binary data is handled using the struct module and binary file modes.

143. What is the purpose of the heapq module?

The heapq module provides functions for implementing heaps based on regular lists.

144. How do you use the shutil module?

The shutil module provides high-level file operations, such as copying and moving files.

145. What is the decimal module used for?

The decimal module provides support for fast and accurate floating-point arithmetic.

146. How do you implement a trie (prefix tree) in Python?

A trie is implemented using nested dictionaries or classes with nodes representing each character.

147. How do you use the bz2 module?

The bz2 module provides support for reading and writing bzip2-compressed files.

148. What is the pdb module used for?

The pdb module is the Python debugger, providing an interactive debugging environment.

149. How do you use the sqlalchemy library?

The sqlalchemy library is used for SQL database management and ORM (Object-Relational Mapping).

150. What are Python’s best practices for writing maintainable code?

Best practices include following PEP 8 guidelines, writing modular and reusable code, using docstrings and comments, implementing unit tests, and leveraging version control systems.

These questions and answers cover a wide range of Python topics, from basic to advanced, providing a solid foundation for interview preparation.

Also read:

https://rawwz.com/blog/top-5-emerging-indian-ai-startups-2024/

Join the conversation

Your email address will not be published. Required fields are marked *