Python Interview Questions
Master your Python interviews with frequently asked questions covering basics, OOP, data structures, Django, and real coding scenarios for freshers and experienced professionals.
Interview Questions for Freshers
1. What is Python? What are the benefits of using Python?
Python is a high-level, interpreted programming language that is designed to be simple and easy to read. Python supports a number of programming paradigms such as object-oriented, procedural, and functional programming. Python has in-built support for modules, exception handling, threads, and memory management, which makes it suitable for solving real-world problems.
Benifits of using Python:
- Simple and Readable Syntax
- General-Purpose Language
- Rapid Application Development
- Large Standard Library
- Extensive Third-Party Ecosystem
- Automatic Memory Management
- Strong Community Support
2. What is PEP-8?
PEP 8 (Python Enhancement Proposal 8) is the official style guide for writing clean and readable Python code. It offers guidelines and best practices for formatting, naming, indentation, spacing, and code structure to ensure consistency across Python projects.
Key PEP 8 Guidelines:
- Use 4 spaces for indentation
- Limit lines to 79 characters
- Use snake_case for variable and function names
- Use PascalCase for class names
- Add blank lines between functions and classes
- Use proper spacing around operators and commas
3. What is a dynamically typed language?
A dynamically typed language is a programming language where the type of a variable is determined at runtime, and not when it is compiled. This means that you don’t have to declare the data type of a variable explicitly, and a variable can hold different types of values at different times.
Example:
1x = 10 // x is a number
2x = 'Hello' // now x is a string
3print(x)4. What is an interpreted language?
An interpreted language is a programming language where the source code is interpreted line by line by the interpreter at the time of execution, as opposed to compilation into machine code. This is a faster way of development because you don’t have to compile the code before execution. Python is one of the most popular interpreted languages.
5. What is scope in Python?
In Python, the scope is the region where the variable or object can be accessed. The scope of a variable determines the visibility and lifetime of the variable during the execution of a program. Python uses namespaces to store the names of variables.
Python variables are accessed according to the LEGB principle:
- Local Scope (L)
Refers to variables defined inside a function. These variables are accessible only within that function.python1def my_function(): 2 x = 10 3 print(x) 4 5my_function() - Enclosing Scope (E)
Refers to variables in the outer (enclosing) function when dealing with nested functions.python1def outer(): 2 x = 10 3 def inner(): 4 print(x) 5 inner() - Global Scope (G)
Refers to variables defined at the top level of a script or module. These variables are accessible throughout the program.python1x = 100 2def show(): 3 print(x) - Built-in Scope (B)
Refers to names pre-defined in Python, such as print(), len(), and range(). These are searched last when resolving variable names.
6. What are built-in data types in Python?
The built-in data types in Python are predefined data types that are provided by the Python language to store and manipulate various types of data. They determine the type of value that a variable holds .
The most common built-in data types in Python are:
- Numberic types (int, float)
- Sequence types (string, list, tuple, range)
- Mapping types (dictionary)
- Set types (set, frozenset)
- Boolean types (bool)
- None type (None)
1# Numeric Types
2integer_value = 10 # int
3float_value = 3.14 # float
4complex_value = 2 + 5j # complex
5
6# Sequence Types
7string_value = "Hello Python" # str
8list_value = [1, 2, 3] # list
9tuple_value = (4, 5, 6) # tuple
10range_value = range(5) # range
11
12# Mapping Type
13dict_value = {"name": "Vishal", "age": 22} # dict
14
15# Set Types
16set_value = {1, 2, 3} # set
17frozenset_value = frozenset([4, 5, 6]) # frozenset
18
19# Boolean Type
20bool_value = True # bool
21
22# None Type
23none_value = None # NoneType
24
25print(type(integer_value))
26print(type(float_value))
27print(type(complex_value))
28print(type(string_value))
29print(type(list_value))
30print(type(tuple_value))
31print(type(range_value))
32print(type(dict_value))
33print(type(set_value))
34print(type(frozenset_value))
35print(type(bool_value))
36print(type(none_value))7. What are lists and tuples? What is the difference between them?
Lists and tuples are sequence data types in Python that are used to store a collection of items. These items can be of different data types such as integers, strings, floats, or even other objects.
Lists are enclosed in square brackets [ ].
Tuples are enclosed in parentheses ().
The main difference between lists and tuples is that lists are mutable (can be modified) while tuples are immutable (cannot be modified).
1my_tuple = ('sara', 6, 5, 0.97)
2my_list = ['sara', 6, 5, 0.97]
3print(my_tuple[0]) # Output: 'sara'
4print(my_list[0]) # Output: 'sara'
5my_tuple[0] = 'ansh' # Error: Tuples are immutable
6my_list[0] = 'ansh' # List gets modified
7print(my_tuple[0]) # Output: 'sara'
8print(my_list[0]) # Output: 'ansh'8. What is the difference between / and // in Python?
In Python, the "/" operator is used for normal division, and it always returns a result that is a floating-point number. The "//" operator is used for floor division, and it always rounds down the result to the nearest whole number.
Example:
1a = 10
2b = 3
3result = a / b
4print(result) # Output: 3.3333333333333335
5result = a // b
6print(result) # Output: 39. What is type casting in Python?
Type casting in Python is referred to as the process of changing a certain data type to another data type. This is done in Python by using built-in functions such as int(), float(), str(), list(), tuple(), and set(). These functions are used to change the type of a variable when the need arises.
Example:
1"# String to Integer
2x = "10"
3y = int(x)
4print(y, type(y))
5
6# Integer to Float
7a = 5
8b = float(a)
9print(b, type(b))
10
11# Integer to String
12num = 100
13text = str(num)
14print(text, type(text))"10. Can we pass a function as an argument in Python?
Yes, we can definitely pass a function as an argument in Python because functions are first-class objects. This means that functions can be assigned to variables, returned from other functions, and passed as arguments to other functions.
Example:
1def greet(name):
2 return f"Hello, {name}"
3
4def process(func, value):
5 return func(value)
6
7result = process(greet, "John")
8print(result) # Hello, John11. What is the difference between mutable and immutable objects in Python ?
In Python, mutable objects are those whose values can be changed after creation, while immutable objects cannot be changed after creation – any change will result in the creation of a new object. Mutable types support in-place modification, while immutable types do not.
Common mutable types include lists, dictionaries, and sets, while immutable types include tuples, strings, and numbers.
Example:
1# Mutable example
2my_list = [1, 2, 3]
3my_list.append(4) # Modifies the same list
4print(my_list)
5
6# Immutable example
7x = 10
8x = x + 5 # Creates a new integer object
9print(x)12. What is indentation and why is it important in Python?
Indentation in Python refers to the spaces or tabs that are used at the start of a line of code to define a block of code. Unlike most other programming languages that use braces {} to define blocks of code, Python uses indentation to define the structure of the code.
Example:
1if x > 0:
2 print("x is positive")
3else:
4 print("x is negative")Why it is important:
Defines code blocks (functions, loops, conditionals)
Improves readability
Enforces clean and consistent code structure
Prevents logical errors
13. What are variables in Python?
Variables in Python are names used to store data values in memory. Variables in Python serve as references to objects, which means that a variable does not store the value but points to the object stored in memory. Python is a dynamically typed language, which means that you do not have to declare the type of a variable. The type of the variable is determined at runtime.
Example:
1x = 10 # Integer
2name = "John" # String
3pi = 3.14 # Float14. What is the difference between == and is in Python?
In Python, `==` is used to check value equality, whereas `is` is used to check object identity, i.e., whether two variables point to the same object in memory. `==` is used to compare the contents of objects, whereas `is` is used to compare the memory locations of objects.
Example:
1a = [1, 2, 3]
2b = [1, 2, 3]
3
4print(a == b) # True (values are equal)
5print(a is b) # False (different objects in memory)15. What is pass in Python?
The pass statement in Python is a null operation, meaning that it does nothing when it is executed. It is used as a placeholder where a statement is required but no code needs to be written yet.
The pass statement is often used in functions, classes, loops, or if statements when you want to add code later.
Example:
1def my_function():
2 pass # Placeholder for future implementation
3for i in range(5):
4 pass # Loop intentionally left empty
5class MyClass:
6 pass # Empty class definition16. What are Python keywords ?
Python keywords are words that have special meanings in Python and cannot be used as variable names, function names, or identifiers.
Example of common Python keywords are:
- if, else, elif
- for, while
- def, return
- class
- try, except, finally
17. What are modules and packages in Python?
Modules in Python are files containing Python code that can be imported and used in other Python files. A package in Python is a directory containing Python modules.
Modules and packages in Python enable modular programming, which is the process of breaking a large program into smaller manageable pieces.
Example:
1math_utils.py
2def add(a, b):
3 return a + b
4
5# Importing the module:
6import math_utils
7print(math_utils.add(2, 3))Advantages of Modules:
- Simplicity – Focus on a small part of the problem.
- Maintainability – Logical separation reduces dependency issues.
- Reusability – Code can be reused across applications.
- Scoping – Each module has its own namespace, avoiding name conflicts.
A package is a collection of related modules organized in a directory (folder). It allows hierarchical structuring of modules using dot notation.
Example:
1math_utils.py
2def add(a, b):
3 return a + b
4
5# Importing the package:
6import math_utils
7print(math_utils.add(2, 3))18. What are Python comments?
Python comments are non-executable statements in code that are used for explaining code logic or temporarily commenting out code. The Python interpreter will ignore comments during execution.
Types of Comments:
Single-line comments: Single-line comments in Python start with the hash symbol (#).
Multi-line comments: Multi-line comments in Python use triple quotes (""" or ''').
Example:
1# This is a single-line comment
2x = 10 # This is an inline comment
3
4"""
5This is a multi-line comment
6used to describe the code.
7"""19. What are global, protected and private attributes in Python?
In Python, attributes and variables can be classified according to their scope and level of accessibility. Although Python does not support strict access modifiers as in other languages, it uses naming conventions to specify accessibility.
Global attributes: Global variables are declared outside any function or class definition and are accessible from anywhere in the program. To change a global variable within a function, the global keyword must be used.
Protected attributes: Protected attributes are prefixed with a single underscore (_). This is a convention that indicates the attribute is intended for internal use within the class and its subclasses. However, it can still be accessed from outside the class.
Private attributes: The private attributes are prefixed with double underscores (__). Python uses name mangling to make them difficult to access directly from outside the class. Trying to access them directly will raise an AttributeError.
Example:
1x = 10 # Global variable
2def update():
3 global x
4 x = 20
5update()
6print(x) # Output: 20
7
8class Person:
9 def __init__(self):
10 self._name = "Sara" # Protected attribute
11
12p = Person()
13print(p._name) # Accessible but not recommended
14
15class Person:
16 def __init__(self):
17 self.__age = 25 # Private attribute
18
19p = Person()
20# print(p.__age) # Raises AttributeErrorInterview Questions for Experienced
1. What are *args and **kwargs in Python?
*args and **kwargs are special features in Python that are used to pass a variable number of arguments to a function.
*args is used to pass a variable number of positional arguments.
**kwargs is used to pass a variable number of keyword arguments.
Example:
1# Example of *args
2def add(*args):
3 return sum(args)
4
5print(add(1, 2, 3, 4))
6
7# Example of **kwargs
8def display(**kwargs):
9 for key, value in kwargs.items():
10 print(f"{key}: {value}")
11
12display(name="John", age=25)2. What are lambda functions in Python?
A lambda function in Python is a short anonymous function that is defined using the lambda keyword. A lambda function can have any number of arguments but only one expression, and it will automatically return the value of that expression. Lambda functions are often used for simple operations, especially when using functions like map(), filter(), and sorted().
Syntax: lambda arguments: expression
Example:
1double = lambda x: x * 2
2print(double(5)) # Output: 103. How do you concatenate two lists in Python?
You can combine two lists in Python using the + operator, the extend() method, the * operator, or the itertools.chain() function.
Example:
1#1. Using the + Operator (Creating a New List)
2list1 = [1, 2]
3list2 = [3, 4]
4
5result = list1 + list2
6print(result) # [1, 2, 3, 4]
7
8#2. Using the extend() Method (Modifying a List)
9list1 = [1, 2]
10list2 = [3, 4]
11
12list1.extend(list2)
13print(list1) # [1, 2, 3, 4]
14
15#3. Using Unpacking (Python 3.5+)
16list1 = [1, 2]
17list2 = [3, 4]
18
19result = [*list1, *list2]
20print(result) # [1, 2, 3, 4]
21
22#4. Using itertools.chain()
23from itertools import chain
24
25list1 = [1, 2]
26list2 = [3, 4]
27
28result = list(chain(list1, list2))
29print(result) # [1, 2, 3, 4]4. What is list comprehension in Python?
List comprehension in Python is a feature that allows the creation of lists within a single line of code. This feature is a more concise and readable way of performing a loop.
Syntax: [expression for item in iterable]
Example:
1#Example (Basic)
2numbers = [1, 2, 3, 4]
3squares = [x * x for x in numbers]
4print(squares) # [1, 4, 9, 16]
5
6#Example with Condition
7numbers = [1, 2, 3, 4, 5, 6]
8evans = [x for x in numbers if x % 2 == 0]
9print(evens) # [2, 4, 6]5. What is the difference between a set and a dictionary ?
In Python, a set is an unordered collection of unique elements, whereas a dictionary is an unordered collection of key-value pairs.
In Python, a set is an unordered collection of unique elements, whereas a dictionary is an unordered collection of key-value pairs.
Example:
1#Set:
2my_set = {1, 2, 3, 3}
3print(my_set) # {1, 2, 3}
4
5#Dictionary:
6my_dict = {"name": "John", "age": 25}
7print(my_dict["name"]) # John6. What is the difference between append() and exten() in Python ?
In Python, append() and extend() are list methods used to add elements, but they behave differently.
Append() adds a single element to the end of the list.
Extend() adds each element of an iterable (like another list) individually to the list.
Example:
1list1 = [1, 2, 3]
2list1.append([4, 5])
3# Result: [1, 2, 3, [4, 5]]
4
5list2 = [1, 2, 3]
6list2.extend([4, 5])
7# Result: [1, 2, 3, 4, 5]7. What is a docstring in Python ?
In Python, a docstring is a string literal that is used to document a function, class, module, or method. The docstring is written using triple quotes (""" """ or ''' ''') and is placed immediately after the definition. Docstrings are used to describe what the code does.
Example:
1def add(a, b):
2 """Return the sum of two numbers."""
3 return a + b
4
5# Accessing the docstring
6print(add.__doc__)8. What are decorators in Python ?
In Python, a decorator is a function that requires another function as an argument, performs some additional tasks on that function, and then returns the function without altering the original code. A decorator in Python is denoted by the@decorator_name syntax.
Example:
1def my_decorator(func):
2 def wrapper():
3 print("Before execution")
4 func()
5 print("After execution")
6 return wrapper
7
8@my_decorator
9def greet():
10 print("Hello")
11
12greet()9. What is a generator in Python ?
In Python, a generator is a kind of function that returns an iterator and uses the "yield" keyword instead of the "return" keyword to produce values one at a time. This is a memory-efficient way of handling large datasets because the values are generated on demand, that is, lazily. Every time a generator function is called, it picks up where it left off.
Example:
1def count_up_to(n):
2 for i in range(1, n + 1):
3 yield i
4
5for num in count_up_to(5):
6 print(num)10. What is the difference between a generator and an iterator ?
An iterator is a class that supports the__iter__() and__next__() methods and is used to iterate over a collection of data, while a generator is a simpler way to create an iterator using a function with theyield keyword. In short, every generator is an iterator, but not every iterator is a generator. Iterators are created using classes and require manual implementation of iteration logic, while generators are more memory-efficient and automatically handle the iteration state.
Example:
1class MyIterator:
2 def __init__(self, n):
3 self.n = n
4 self.current = 1
5
6 def __iter__(self):
7 return self
8
9 def __next__(self):
10 if self.current <= self.n:
11 value = self.current
12 self.current += 1
13 return value
14 else:
15 raise StopIteration
16
17for i in MyIterator(3):
18 print(i)11. What is the difference between a class method, a static method, and an instance method ?
In Python, the distinction between an instance method, class method, and static method depends on what they deal with and how they are declared:
Instance Method: It deals with the instance (object) data and requires
selfas the first argument. It has access to and can modify the object attributes.Class Method: It deals with the class itself and requires
clsas the first argument. It is declared using@classmethodand can modify the class attributes.Static Method: It does not have access to the instance or class data directly. It is like a normal function within a class and is declared using
@staticmethod.
Example:
1class Example:
2 class_variable = 10
3
4 def __init__(self, value):
5 self.instance_variable = value
6
7 # Instance Method
8 def instance_method(self):
9 return self.instance_variable
10
11 # Class Method
12 @classmethod
13 def class_method(cls):
14 return cls.class_variable
15
16 # Static Method
17 @staticmethod
18 def static_method(x, y):
19 return x + y
20
21
22obj = Example(5)
23
24print(obj.instance_method()) # Access instance variable
25print(Example.class_method()) # Access class variable
26print(Example.static_method(3, 4)) # Independent calculation12. What is method overloading in Python?
Method overloading is the process of defining multiple methods with the same name but different parameters in the same class. Python does not support method overloading like other programming languages. Python supports method overloading using default arguments or variable-length arguments such as*args and **kwargs.
Example:
1class Calculator:
2 def add(self, a, b=0, c=0):
3 return a + b + c
4
5calc = Calculator()
6
7print(calc.add(5)) # 5
8print(calc.add(5, 3)) # 8
9print(calc.add(5, 3, 2)) # 1013. What is method overriding in Python?
Method overriding occurs when the child class has its own implementation of a method that is already defined in its parent class. It is used in inheritance to alter or extend the functionality of the parent class method. The method in the child class must have the same name and parameters as in the parent class.
Example:
1class Animal:
2 def sound(self):
3 return "Animal makes a sound"
4
5class Dog(Animal):
6 def sound(self):
7 return "Dog barks"
8
9obj = Dog()
10print(obj.sound()) # Dog barks14. What is inheritance in Python?
Inheritance is an object-oriented programming technique where one class (child class) inherits the characteristics of another class (parent class). Inheritance is a mechanism in object-oriented programming that supports code reusability and helps the child class extend or override the parent class.
Example:
1class Parent:
2 def greet(self):
3 return "Hello from Parent"
4
5class Child(Parent):
6 def speak(self):
7 return "Hello from Child"
8
9obj = Child()
10print(obj.greet()) # Inherited method
11print(obj.speak()) # Child method15. What is polymorphism in Python?
Polymorphism in Python: This is an object-oriented programming concept where the same method name is used differently for different objects. It provides the ability to define methods with the same name in different classes, which is achieved by method overriding or duck typing.
Example:
1class Bird:
2 def sound(self):
3 return "Bird chirps"
4
5class Dog:
6 def sound(self):
7 return "Dog barks"
8
9for animal in (Bird(), Dog()):
10 print(animal.sound())16. What is encapsulation in Python?
Encapsulation in Python is an object-oriented programming concept that limits direct access to the data and methods of a class in order to safeguard it from being modified inadvertently. It is implemented with the help of access modifiers such as public, protected (_), and private (__), and it assists in hiding data and controlling access to it.
Example:
1class Person:
2 def __init__(self, name, age):
3 self.name = name # Public
4 self._salary = 50000 # Protected
5 self.__age = age # Private
6
7 def get_age(self):
8 return self.__age
9
10obj = Person("John", 30)
11print(obj.name)
12print(obj.get_age())17. What is abstraction in Python?
Abstraction in Python is a concept of object-oriented programming that involves hiding the details of implementation and only showing the necessary characteristics of an object. This is used in Python through the use of abstract classes and methods in theabc module.
Example:
1from abc import ABC, abstractmethod
2
3class Shape(ABC):
4 @abstractmethod
5 def area(self):
6 pass
7
8class Circle(Shape):
9 def __init__(self, radius):
10 self.radius = radius
11
12 def area(self):
13 return 3.14 * self.radius * self.radius
14
15obj = Circle(5)
16print(obj.area())18. What is the difference between @staticmethod and @classmethod?
The main difference between @staticmethod and @classmethod lies in what they access. A static method does not have an implicit first argument and cannot access or change class or instance variables. It is just like a normal function defined in a class. A class method receives cls as the first argument and can access or modify class-level attributes.
Example:
1class Example:
2 count = 0
3
4 def __init__(self):
5 Example.count += 1
6
7 @classmethod
8 def get_count(cls):
9 return cls.count
10
11 @staticmethod
12 def add(a, b):
13 return a + b
14
15obj1 = Example()
16obj2 = Example()
17
18print(Example.get_count()) # 2
19print(Example.add(3, 4)) # 719. What is the purpose of the self keyword in Python?
The self keyword in Python is the current instance of a class. It is used within instance methods to access and change the object's attributes and call other methods of the same class. It must be the first parameter of an instance method, which enables each object to hold its own data.
Example:
1class Person:
2 def __init__(self, name):
3 self.name = name
4
5 def greet(self):
6 return "Hello, " + self.name
7
8obj = Person("John")
9print(obj.greet())20. What is exception handling in Python?
Exception handling in Python is a process used to handle runtime errors in a way that the program does not crash unexpectedly. It is done by using try, except, else, and finally blocks, allowing developers to catch errors and execute alternative code when exceptions occur.
Example:
1try:
2 num = int(input("Enter a number: "))
3 result = 10 / num
4 print(result)
5except ZeroDivisionError:
6 print("Cannot divide by zero")
7except ValueError:
8 print("Invalid input")
9finally:
10 print("Execution completed")21. What is the difference between raise and assert?
The raise keyword is used to manually trigger an exception at any point in the program, allowing developers to handle custom errors explicitly. On the other hand, assert is used for debugging to check whether a condition is true; if the condition is false, it raises an AssertionError. Additionally, assertions can be turned off when executing Python in optimized mode, whereas raise is always executed.
Example:
1# Using raise
2age = -5
3if age < 0:
4 raise ValueError("Age cannot be negative")
5
6# Using assert
7num = 10
8assert num > 0, "Number must be positive"22. What is the difference between pass, continue, and break?
The pass statement is a null operation that does nothing and is used as a placeholder in loops, functions, or classes. The continue statement skips the current iteration of a loop and moves to the next iteration. The break statement immediately terminates the loop and transfers control to the statement following the loop.
Example:
1for i in range(5):
2 if i == 1:
3 continue
4 if i == 3:
5 break
6 if i == 4:
7 pass
8 print(i)
9
10# Output:
11# 0
12# 242. What are virtual environments in Python?
A virtual environment in Python is a sandbox or isolated environment that enables you to install and manage project-specific dependencies independently of the global Python installation. This is useful in preventing version conflicts between projects and ensuring that each project has its required packages without interfering with other projects. Virtual environments can be created using the venv module or tools like virtualenv.
Example (Creating a virtual environment):
1# Create virtual environment
2python -m venv myenv
3
4# Activate (Windows)
5myenv\Scripts\activate
6
7# Activate (Mac/Linux)
8source myenv/bin/activate24. What is pip?
pip is a package manager for Python that is used to install, upgrade, and manage external libraries from the Python Package Index (PyPI). pip is used to add third-party packages to projects.
Example:
1# Install a package
2pip install requests
3
4# Upgrade a package
5pip install --upgrade requests
6
7# List installed packages
8pip listAdvanced Interview Questions
1. How does memory management work in Python?
Memory management in Python is automatically taken care of by the Python Memory Manager. It employs a technique of reference counting along with a cyclic garbage collector to manage memory allocation and deallocation. When the reference count of an object reaches zero, the memory is automatically deallocated. Also, Python’s garbage collector takes care of removing cyclic links that are not removed by reference counting.
Example:
1import gc
2
3# Reference counting example
4a = [1, 2, 3]
5b = a
6
7del a
8del b # Object is removed when reference count becomes zero
9
10# Manually trigger garbage collection
11gc.collect()2. What is reference counting?
Reference counting is a memory management system that is employed by Python, where every object maintains a count of the number of references to it. Each time a new reference to an object is created, the reference count of the object is incremented, and when a reference to the object is deleted, the reference count is decremented. When the reference count reaches zero, the memory space allocated to the object is automatically released.
Example:
1import sys
2
3a = []
4print(sys.getrefcount(a)) # Reference count increases
5
6b = a
7print(sys.getrefcount(a)) # Count increases again
8
9del b
10print(sys.getrefcount(a)) # Count decreases3. What is garbage collection in Python?
Garbage collection is the process of automatically freeing memory occupied by objects that are no longer in use. Python primarily uses reference counting to manage memory.
It also includes a cyclic garbage collector to detect and remove objects involved in reference cycles. Thegc module is used to control and inspect garbage collection.
Example:
1import gc
2
3class Node:
4 def __init__(self):
5 self.ref = None
6
7# Create cyclic reference
8a = Node()
9b = Node()
10a.ref = b
11b.ref = a
12
13# Remove references
14 del a
15 del b
16
17# Manually trigger garbage collection
18gc.collect()4. What is the Global Interpreter Lock (GIL)?
The Global Interpreter Lock (GIL) is a mechanism in CPython that allows only one thread to execute Python bytecode at a time.
It ensures thread safety for memory management but limits true parallelism in CPU-bound multi-threaded programs.
It does not significantly affect I/O-bound programs because the GIL is released during I/O operations.
For CPU-bound parallelism, the
multiprocessingmodule can be used instead of threading.
5. What are Python’s threading limitations?
Due to the Global Interpreter Lock (GIL) in CPython, only one thread can execute Python bytecode at a time.
Threads do not provide true parallelism for CPU-bound tasks.
Context switching between threads can add overhead and reduce performance.
For CPU-intensive tasks, the
multiprocessingmodule is preferred over threading.
6. What is multiprocessing in Python?
Multiprocessing is a technique in Python that allows multiple processes to run simultaneously using separate memory spaces.
It achieves true parallelism by bypassing the Global Interpreter Lock (GIL).
It is mainly used for CPU-bound tasks to improve performance.
The
multiprocessingmodule provides support for creating and managing processes.
Example:
1from multiprocessing import Process
2
3def square(num):
4 print(num * num)
5
6if __name__ == "__main__":
7 p1 = Process(target=square, args=(5,))
8 p2 = Process(target=square, args=(10,))
9
10 p1.start()
11 p2.start()
12
13 p1.join()
14 p2.join()7. What is asyncio?
Asyncio is a Python library used to write concurrent code using asynchronous programming with the
asyncandawaitkeywords.It is mainly used for I/O-bound and high-level structured network code.
It runs tasks concurrently using a single-threaded event loop.
Asyncio improves performance for I/O-bound operations like API calls, database queries, and file handling.
Example:
1import asyncio
2
3async def greet():
4 print("Hello")
5 await asyncio.sleep(1)
6 print("World")
7
8asyncio.run(greet())8. What are coroutines in Python?
Coroutines in Python are special functions defined using the async def syntax that can pause and resume execution. They use the await keyword to suspend execution until an awaited task completes, enabling asynchronous and non-blocking programming, typically managed by an event loop such as asyncio.
Example:
1import asyncio
2
3async def greet():
4 print("Hello")
5 await asyncio.sleep(1)
6 print("World")
7
8asyncio.run(greet())9. What are context managers?
Context managers are objects that manage resources automatically during execution using the
withstatement.They ensure proper setup and cleanup of resources such as files, database connections, or network sockets.
They are implemented using the
__enter__and__exit__methods.
Example:
1# Using built-in context manager
2with open("file.txt", "w") as f:
3 f.write("Hello World")
4
5# Custom context manager
6class MyContext:
7 def __enter__(self):
8 print("Entering")
9 return self
10
11 def __exit__(self, exc_type, exc_val, exc_tb):
12 print("Exiting")
13
14with MyContext():
15 print("Inside block")10. What is the difference between __str__ and __repr__?
The __str__ method returns a readable, user-friendly string representation of an object and is used by print(). The __repr__ method returns an unambiguous, developer-focused representation of the object, ideally one that can recreate the object. If __str__ is not defined, Python falls back to __repr__.
Example:
1class Person:
2 def __init__(self, name):
3 self.name = name
4
5 def __str__(self):
6 return f"Person name is {self.name}"
7
8 def __repr__(self):
9 return f"Person('{self.name}')"
10
11obj = Person("Vishal")
12print(str(obj)) # Calls __str__
13print(repr(obj)) # Calls __repr__11. What is monkey patching?
Monkey patching is a technique in Python where a class or module is modified at runtime by adding, changing, or replacing methods or attributes.
It allows dynamic behavior changes without modifying the original source code.
It is commonly used in testing, debugging, or extending third-party libraries.
Example:
1class Person:
2 def greet(self):
3 return "Hello"
4
5# Monkey patching
6def new_greet(self):
7 return "Hi there!"
8
9Person.greet = new_greet
10
11obj = Person()
12print(obj.greet()) # Hi there!12. What is metaclass in Python?
A metaclass is a class of a class, meaning it defines how classes themselves behave.
Just as classes define the behavior of objects, metaclasses define the behavior of classes.
In Python, the default metaclass is
type.Metaclasses are commonly used to customize class creation, enforce rules, or modify class attributes dynamically.
Example:
1class MyMeta(type):
2 def __new__(cls, name, bases, dct):
3 dct['greet'] = lambda self: "Hello from Metaclass"
4 return super().__new__(cls, name, bases, dct)
5
6class MyClass(metaclass=MyMeta):
7 pass
8
9obj = MyClass()
10print(obj.greet())13. What is the difference between CPython, Jython, and PyPy?
CPython is the standard and most widely used implementation of Python, written in C, and it uses the Global Interpreter Lock (GIL).
Jython is implemented in Java and runs on the Java Virtual Machine (JVM), allowing seamless integration with Java libraries.
PyPy is an alternative implementation written in RPython that includes a Just-In-Time (JIT) compiler to improve performance.
CPython focuses on compatibility and stability, Jython focuses on Java interoperability, and PyPy focuses on speed and performance optimization.
14. How does Python handle memory allocation internally?
Python uses a private heap to manage memory, and all Python objects and data structures are stored there.
Memory management is handled by the Python Memory Manager, which controls allocation and deallocation.
CPython uses an internal allocator called
pymallocto efficiently allocate small objects.Memory is managed using reference counting along with a cyclic garbage collector to clean up unused objects.
15. What is time complexity of common Python data structures?
The time complexity of common Python data structures depends on their internal implementation (arrays or hash tables). Below are the average-case complexities:
List: Access O(1), Append O(1) amortized, Insert/Delete O(n), Search O(n).
Tuple: Access O(1), Search O(n).
Dictionary: Access O(1), Insert O(1), Delete O(1), Search O(1) average case.
Set: Add O(1), Remove O(1), Search O(1) average case.
16. How would you optimize a slow Python program?
To optimize a slow Python program, first identify performance bottlenecks using profiling tools such as cProfile or time measurements. Focus on improving inefficient algorithms and data structures, since algorithmic complexity has the biggest impact. Use built-in functions and libraries as they are implemented in C and are faster. Reduce unnecessary computations, avoid redundant loops, and use list comprehensions or generators where appropriate. For CPU-bound tasks, consider multiprocessing, and for I/O-bound tasks, use asynchronous programming. If needed, performance can also be improved using tools like PyPy, C extensions, or libraries such as NumPy.
17. How does Python handle mutable default arguments internally?
In Python, default argument values are evaluated only once at the time the function is defined, not each time the function is called. If the default value is mutable (like a list or dictionary), the same object is reused across multiple function calls. This can lead to unexpected behavior because changes made to the object persist between calls.
Example:
1def add_item(item, my_list=[]):
2 my_list.append(item)
3 return my_list
4
5print(add_item(1)) # [1]
6print(add_item(2)) # [1, 2] (unexpected behavior)Correct approach:
1def add_item(item, my_list=None):
2 if my_list is None:
3 my_list = []
4 my_list.append(item)
5 return my_listRelated Articles
React JS Interview Questions
Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.
FrontendJavaScript Interview Questions
Prepare for your next tech interview with the most asked JavaScript interview questions and answers. It includes basic to advanced concepts, coding problems, and real-world scenarios for freshers and experienced developers.