Python technical interview questions and answers are widely asked in software development, data science, automation, and machine learning roles. Python is one of the most popular languages due to its simplicity and power, so companies expect candidates to understand core topics like variables, loops, functions, OOP, modules, file handling, exceptions, and libraries. Companies like TCS, Infosys, Cognizant, Capgemini, and Wipro frequently include Python questions in interviews and online tests. This guide provides clear explanations for the most important Python questions, making it useful for freshers preparing for placement interviews as well as experienced developers. You can also download Python interview PDFs and practice coding exercises to strengthen your preparation.
Python developers can enhance their capabilities by exploring data science applications and machine learning implementations
1. What is Python?
Answer: Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many
Show Answer
Hide Answer
2. Is there a tool to help find bugs or perform static analysis?
Answer: Yes.
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style.
Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.
Show Answer
Hide Answer
3. How can I find the methods or attributes of an object?
Answer: For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.
Show Answer
Hide Answer
5. How do I convert a number to a string?
Answer: To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details.
Show Answer
Hide Answer
6. Is there a scanf() or sscanf() equivalent?
Answer: Not as such.
For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator.
For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task.
Show Answer
Hide Answer
7. What's a negative index?
Answer: Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].
Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.
Show Answer
Hide Answer
8. What is a method?
Answer: A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition:
class C:
def meth (self, arg):
return arg*2 + self.attribute
Show Answer
Hide Answer
9. What is self?
Answer: Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).
Show Answer
Hide Answer
10. Where is the math.py (socket.py, regex.py, etc.) source file?
Answer: There are (at least) three kinds of modules in Python:
1. modules written in Python (.py);
2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3. modules written in C and linked with the interpreter; to get a list of these, type:
import sys
print sys.builtin_module_names
Show Answer
Hide Answer
11. How do I delete a file? (And other file questions...)
Answer: Use os.remove(filename) or os.unlink(filename);
Show Answer
Hide Answer
13. Can I create my own functions in C?
Answer: Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.
Show Answer
Hide Answer
14. How do I generate random numbers in Python?
Answer: The standard module random implements a random number generator. Usage is simple:
import random
random.random()
This returns a random floating point number in the range [0, 1).
Show Answer
Hide Answer
15. Can I create my own functions in C++?
Answer: Yes, using the C compatibility features found in C++. Place extern "C" { ... } around the Python include files and put extern "C" before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.
Show Answer
Hide Answer
16. How can I execute arbitrary Python statements from C?
Answer: The highest-level function to do this is PyRun_SimpleString() which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including SyntaxError). If you want more control, use PyRun_String(); see the source for PyRun_SimpleString() in Python/pythonrun.c.
Show Answer
Hide Answer
17. How can I evaluate an arbitrary Python expression from C?
Answer: Call the function PyRun_String() from the previous question with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value.
Show Answer
Hide Answer
18. How do I interface to C++ objects from Python?
Answer: Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.
Show Answer
Hide Answer
19. Where is Freeze for Windows?
Answer: "Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.
Show Answer
Hide Answer
20. What is metaprogramming in Python and how is it implemented?
Answer: Metaprogramming allows for writing programs that manipulate other programs, typically through metaclasses and decorators, which can dynamically alter class behavior.
Show Answer
Hide Answer
21. How does Pythons Global Interpreter Lock (GIL) affect multi-threading?
Answer: The GIL ensures that only one thread executes Python bytecode at a time, which can lead to performance limitations in CPU-bound multi-threaded programs, encouraging the use of multiprocessing instead.
Show Answer
Hide Answer
22. Explain how to implement a custom iterator in Python.
Answer: To create a custom iterator, define a class with __iter__() returning self and __next__() providing the next value, raising StopIteration when done.
Show Answer
Hide Answer
23. What are Python coroutines and how do they differ from functions?
Answer: Coroutines are defined with async def, allowing them to pause execution and yield control back to the event loop, facilitating asynchronous programming.
Show Answer
Hide Answer
24. Discuss the principles and implementation of context managers.
Answer: Context managers are implemented using __enter__ and __exit__ methods, utilizing the with statement to ensure resource management and cleanup after use.
Show Answer
Hide Answer
25. What is the purpose of descriptors in Python?
Answer: Descriptors control attribute access by defining methods __get__, __set__, and __delete__, enabling property-like behavior in class attributes.
Show Answer
Hide Answer
26. Explain the difference between *args and **kwargs in function definitions.
Answer: *args allows for variable-length non-keyword arguments, while **kwargs allows for variable-length keyword arguments, providing flexibility in function calls.
Show Answer
Hide Answer
27. How can Python's functools module be used to optimize function calls
Answer: The functools module includes lru_cache to cache results of expensive function calls, improving performance for repeated calls with the same attributes.
Show Answer
Hide Answer
28. What are the advantages and drawbacks of using Python's asyncio library
Answer: asyncio allows for writing concurrent code using async/await, improving I/O-bound task performance, but adds complexity and is not suitable for CPU-bound tasks.
Show Answer
Hide Answer
29. Describe how to implement and use a singleton pattern in Python.
Answer: A singleton can be implemented by overriding __new__ in a class, ensuring that only one instance is created, thus controlling the object’s instantiation.
Show Answer
Hide Answer
30. Explain metaprogramming in Python and its implementation
Answer: Metaprogramming allows for writing programs that manipulate other programs, typically through metaclasses and decorators, which can dynamically alter class behavior.
Show Answer
Hide Answer
31. Discuss how the Global Interpreter Lock (GIL) affects multi-threading in Python
Answer: The GIL ensures that only one thread executes Python bytecode at a time, which can lead to performance limitations in CPU-bound multi-threaded programs, encouraging the use of multiprocessing instead.
Show Answer
Hide Answer
32. Detail how to implement a custom iterator in Python
Answer: To create a custom iterator, define a class with __iter__() returning self and __next__() providing the next value, raising StopIteration when done.
Show Answer
Hide Answer
33. Describe Python coroutines and their differences from functions
Answer: Coroutines are defined with async def, allowing them to pause execution and yield control back to the event loop, facilitating asynchronous programming.
Show Answer
Hide Answer
34. Discuss the principles and implementation of context managers
Answer: Context managers are implemented using __enter__ and __exit__ methods, utilizing the with statement to ensure resource management and cleanup after use.
Show Answer
Hide Answer
35. What is the role of descriptors in Python
Answer: Descriptors control attribute access by defining methods __get__, __set__, and __delete__, enabling property-like behavior in class attributes.
Show Answer
Hide Answer
36. Explain the differences between *args and **kwargs in function definitions
Answer: *args allows for variable-length non-keyword arguments, while **kwargs allows for variable-length keyword arguments, providing flexibility in function calls.
Show Answer
Hide Answer
37. Discuss how Python's functools module can optimize function calls
Answer: The functools module includes lru_cache to cache results of expensive function calls, improving performance for repeated calls with the same attributes.
Show Answer
Hide Answer
38. Outline the advantages and drawbacks of using Python's asyncio library
Answer: asyncio allows for writing concurrent code using async/await, improving I/O-bound task performance, but adds complexity and is not suitable for CPU-bound tasks.
Show Answer
Hide Answer
39. Describe how to implement a singleton pattern in Python
Answer: A singleton can be implemented by overriding __new__ in a class, ensuring that only one instance is created, thus controlling the object’s instantiation.
Show Answer
Hide Answer
40. Explain the difference between deep copy and shallow copy in Python
Answer: A shallow copy creates a new object but inserts references into it to the objects found in the original. A deep copy creates a new object and recursively adds copies of nested objects found in the original, making it completely independent of the original.
Show Answer
Hide Answer
41. How does the Python Global Interpreter Lock (GIL) affect multi-threading
Answer: The GIL in Python allows only one thread to execute at a time per interpreter process, which can limit the performance of CPU-bound multi-threaded programs. However, it does not affect I/O-bound multi-threaded programs significantly.
Show Answer
Hide Answer
42. What are Python decorators and how are they used
Answer: Decorators are a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. They are used by prefixing a function with the @ symbol followed by the decorator function.
Show Answer
Hide Answer
43. Describe how Python handles memory management
Answer: Python uses automatic memory management, primarily via reference counting and garbage collection. Reference counting keeps track of the number of references to each object in memory, and when an object’s reference count drops to zero, the memory is freed. Garbage collection is used to detect and clean up cycles of references that cannot be freed by reference counting alone.
Show Answer
Hide Answer
44. How would you implement a singleton pattern in Python
Answer: A singleton pattern in Python can be implemented by defining a class with a class-level attribute that holds the single instance. The __new__ method can be overridden to ensure that no more than one instance is created.
Show Answer
Hide Answer
45. Explain the difference between @staticmethod and @classmethod in Python
Answer: @staticmethod defines a method that does not require an instance or class reference and cannot modify object state or class state. @classmethod receives the class as the first argument and can modify class state that applies across all instances.
Show Answer
Hide Answer
46. How would you optimize a Python code to reduce memory usage
Answer: To optimize memory usage in Python, you can use generators instead of lists for large data sets, use built-in data structures that are more memory-efficient, apply the del statement to delete unnecessary variables, and use the slots feature in classes to prevent the creation of instance dictionaries.
Show Answer
Hide Answer
47. What is the purpose of the yield keyword in Python
Answer: The yield keyword in Python is used in a function to make it a generator, which can return a value and later resume execution from where it left off. This allows for the creation of iterators in a memory-efficient manner.
Show Answer
Hide Answer
48. Explain how Python’s list comprehension works and provide an example of its use
Answer: List comprehension provides a concise way to create lists by embedding an expression inside square brackets, optionally followed by a for clause, and then one or more for or if clauses. Example: [x**2 for x in range(10) if x % 2 == 0] returns [0, 4, 16, 36, 64].
Show Answer
Hide Answer
49. How do you handle exceptions in Python and how can you create custom exceptions
Answer: Exceptions in Python are handled using try-except blocks. Custom exceptions can be created by defining a new class that inherits from the built-in Exception class, and raising it using the raise statement.
Show Answer
Hide Answer
50. Explain the difference between deep copy and shallow copy in Python
Answer: A shallow copy creates a new object but inserts references into it to the objects found in the original. A deep copy creates a new object and recursively adds copies of nested objects found in the original, making it completely independent of the original.
Show Answer
Hide Answer
51. How does the Python Global Interpreter Lock (GIL) affect multi-threading
Answer: The GIL in Python allows only one thread to execute at a time per interpreter process, which can limit the performance of CPU-bound multi-threaded programs. However, it does not affect I/O-bound multi-threaded programs significantly.
Show Answer
Hide Answer
52. What are Python decorators and how are they used
Answer: Decorators are a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. They are used by prefixing a function with the @ symbol followed by the decorator function.
Show Answer
Hide Answer
53. Describe how Python handles memory management
Answer: Python uses automatic memory management, primarily via reference counting and garbage collection. Reference counting keeps track of the number of references to each object in memory, and when an object’s reference count drops to zero, the memory is freed. Garbage collection is used to detect and clean up cycles of references that cannot be freed by reference counting alone.
Show Answer
Hide Answer
54. How would you implement a singleton pattern in Python
Answer: A singleton pattern in Python can be implemented by defining a class with a class-level attribute that holds the single instance. The __new__ method can be overridden to ensure that no more than one instance is created.
Show Answer
Hide Answer
55. Explain the difference between @staticmethod and @classmethod in Python
Answer: @staticmethod defines a method that does not require an instance or class reference and cannot modify object state or class state. @classmethod receives the class as the first argument and can modify class state that applies across all instances.
Show Answer
Hide Answer
56. How would you optimize Python code to reduce memory usage
Answer: To optimize memory usage in Python, you can use generators instead of lists for large data sets, use built-in data structures that are more memory-efficient, apply the del statement to delete unnecessary variables, and use the slots feature in classes to prevent the creation of instance dictionaries.
Show Answer
Hide Answer
57. What is the purpose of the yield keyword in Python
Answer: The yield keyword in Python is used in a function to make it a generator, which can return a value and later resume execution from where it left off. This allows for the creation of iterators in a memory-efficient manner.
Show Answer
Hide Answer
58. Explain how Python’s list comprehension works and provide an example of its use
Answer: List comprehension provides a concise way to create lists by embedding an expression inside square brackets, optionally followed by a for clause, and then one or more for or if clauses. Example: [x**2 for x in range(10) if x % 2 == 0] returns [0, 4, 16, 36, 64].
Show Answer
Hide Answer
59. How do you handle exceptions in Python and how can you create custom exceptions
Answer: Exceptions in Python are handled using try-except blocks. Custom exceptions can be created by defining a new class that inherits from the built-in Exception class, and raising it using the raise statement.
Show Answer
Hide Answer
60. What is the difference between is and == in Python
Answer: The == operator compares the values of two objects, while the is operator compares their identities, i.e., whether they refer to the same object in memory.
Show Answer
Hide Answer
61. Explain the purpose of the __init__ method in Python
Answer: The __init__ method in Python is a constructor that is called automatically when a new instance of a class is created. It initializes the instance’s attributes.
Show Answer
Hide Answer
62. What are Python’s magic methods and how are they useful
Answer: Magic methods in Python are special methods that start and end with double underscores, such as __init__, __str__, and __add__. They are used to override or extend the behavior of operators and built-in functions for user-defined objects.
Show Answer
Hide Answer
63. How does Python’s garbage collector work and how can it be controlled
Answer: Python’s garbage collector works by reference counting and detecting cyclic references that cannot be freed by reference counting alone. It can be controlled using the gc module, which allows you to enable/disable garbage collection and manually trigger collection.
Show Answer
Hide Answer
64. Describe how Python manages namespaces and scope
Answer: Python uses namespaces to keep track of variable names. The scope defines the region of a program where a namespace is directly accessible. The LEGB rule (Local, Enclosing, Global, Built-in) determines the order in which namespaces are searched.
Show Answer
Hide Answer
65. How would you reverse a string in Python
Answer: A string in Python can be reversed using slicing: reversed_string = original_string[::-1]. This creates a new string that is a reversed copy of the original.
Show Answer
Hide Answer
66. What are Python’s iterators and how do they differ from generators
Answer: Iterators are objects that implement the iterator protocol, with methods __iter__() and __next__(). Generators are a special type of iterator that are defined with a function and use yield to produce values lazily, one at a time.
Show Answer
Hide Answer
67. Explain the concept of metaclasses in Python and their use cases
Answer: A metaclass in Python is a class of a class, meaning it defines the behavior of a class object. Metaclasses are used to create frameworks, enforce class creation rules, or modify class attributes.
Show Answer
Hide Answer
68. How would you merge two dictionaries in Python
Answer: In Python 3.9 and later, two dictionaries can be merged using the | operator: merged_dict = dict1 | dict2. In earlier versions, the update() method or dictionary unpacking with ** can be used.
Show Answer
Hide Answer
69. Describe the difference between synchronous and asynchronous programming in Python
Answer: Synchronous programming blocks the execution until the current operation completes, while asynchronous programming allows other operations to run before the previous one completes. Python supports asynchronous programming using the async/await syntax.
Show Answer
Hide Answer