Mastering Python Interview questions and answers in this job market is essential for standing out among the competitive pool of candidates.
This guide lists the top best100 Python interview questions and answers for freshers, covering basics, coding, OOP, and real interview scenarios.
Top 100 Best Python Interview Questions and Answers For Freshers
Whether you are a seasoned developer or a recent graduate, entering into job market, preparing Python interview questions and answers is the key to upgrading yourself for cracking a lucrative Python job.
If you want to master OOP concepts in Python, check out this curated list of 50+ Python OOPs Interview Questions and Answers — complete with Pro Tips to help you confidently crack Python job interviews.
Q1. What is Python?
Python is an interpreted, high-level, general-purpose programming language that is widely used for various purposes such as web development, scientific computing, data analysis, artificial intelligence, and more. It is known for its simplicity, readability, and ease of use, making it a popular choice among developers and non-developers.
Q2. What are Python's key features?
Python's key features are easy to learn, a high-level interpreted language, extensive libraries, a large community, scripting, rapid development, and extensive documentation. Another great feature is that it is a cross-platform, that works on Windows, Mac, and Linux.
Q3. What are variables in python?
Variables in Python are used to store and manipulate data in a program. It can be thought of as labelled containers that hold values. Python is dynamically typed, which means you don’t need to declare the data type of a variable explicitly—Python automatically detects it at runtime. For example:
age = 25
print(age) # Output: 25
Q4. What are Python's data types?
Data types in Python tell what kind of value a variable holds. For example, int
is a whole number, float
is a decimal number, str
is for text, list
for a collection of items, tuple
for an unchangeable group of items, dict
key value pairs, set
for unique items, bool
for true/false, and NoneType
for none. Here's a great thing that you don't have to define the type because Python does it automatically.
Q5. What is the difference between list
and tuple
?
The main difference between list
and tuple
is that lists
are mutable, tuples
are immutable. LIst
uses square brackets []
while tuple
uses parentheses ().
Another key takeaway is Lists
are suitable for situations where data needs to be modified, while tuples
are suitable for situations where data should remain constant.
Q6. How do you create a virtual environment in Python?
Creating a virtual environment in Python is a key step to isolating project dependencies and avoiding conflicts between packages.
At first, create the environment:
python -m venv env
.\env\Scripts\activate
or on macOS/Linux: source env/bin/activate
Then deactivate when done:
deactivate
If you want project setup, best practices, and environment isolation for Django development, check out this full step-by-step guide on setting up Django with a virtual environment.
Q7. What is indentation in Python?
Indentation in Python is used to define the structure of the code. It is mainly used to denote block-level structure, such as in loops, conditional statements, functions, and classes. For example :
if True:
print("This is indented")
print("This is also indented")
print("This is not indented")
print
statements within the if
block are indented to denote that they belong to the if
statement. The last print statement is not indented, indicating it's outside the if
block.Q8. What is a dictionary in Python?
A dictionary is an unordered collection of key-value pairs. It's a mutable data type that allows you to store and manipulate data in a flexible way.
A collection of key-value pairs is defined using the curly braces {}
. For example :
person = {"name": "Alice", "age": 30}
print(person["name"]) # Output: Alice
person
is a dictionary with two key-value pairs: "name"
is the key for the value "Alice"
, and "age"
is the key for the value 30
. When you use person["name"]
, it retrieves the value associated with the key "name"
, which is "Alice"
.Q9. How do you write comments in Python?
comments are used to add notes or explanations to the code. There are two types of comments: single-line comments and multi-line comments. You can make your code more readable, maintainable, and understandable by using comments effectively.
Q10. What is indentation, and why is it important in Python?
Indentation in Python is the use of spaces or tabs at the beginning of a line to define code blocks. It’s important because Python uses indentation to determine the grouping of statements, unlike other languages that use braces {}
. Proper indentation ensures the code runs correctly and improves readability.
Here's a simple example showing indentation in Python:
if 5 > 2:
print("Five is greater than two") # This line is indented and part of the if block
print("This line is outside the if block") # Not indented, runs always
print
inside the if
, Python will give an error. Indentation shows which code belongs to the if
statement.Q11. What are Python keywords?
Python keywords are reserved words that have special meanings in the Python language. They are used to define the syntax and structure of Python code. There are numerous examples of Python keywords such as control flow, logical, definition, definition, import, exception, etc., keywords. Python keywords can not be used as names or identifiers. If it is used, then the result will show SyntaxError.
Q12. What is the difference between global and local variables in python?
The difference between global and local variables in Python is that global variables are defined outside of any function or class, whereas local variables are defined inside a function or class. Global variables can be accessed and modified from anywhere, while local variables only accessible within the function or class where they are defined and cease to exist once the function or class execution is completed.
Q13. What are Python functions?
Functions in Python are blocks of code that can be executed multiple times from different parts of your program. They are used to organise, reuse code and improve readability. you can define the reusable blocks of code using def,
or you can use built-in functions like print()
, len()
, and type()
.
Q14. What is the use of return
in a function?
The return
statement in Python functions is used to send back values from a function to the caller and ends the function execution and outputs the specified value, allowing you to use that value elsewhere in your code. For example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
return
sends the sum of a
and b
back so it can be stored in result
and printed.Q15. How do you handle exceptions in Python?
Exceptions in Python are events that occur during the execution of a program, such as division by zero or out-of-range values. You can handle exceptions using try
, except
, else
, and finally
blocks. You can write more robust and reliable code that can handle unexpected errors and provide useful feedback to users by handling exceptions properly.
Q16. What are modules in Python?
Modules in Python are files containing code that can be imported using import.
They are pre-written code libraries that provide a set of related functions, classes, and variables. They allow you to organise, reuse code and extend functionality. Python has built-in modules like math
, datetime
, and os
. you can write more efficient, maintainable, and readable code.
Q17. What is __init__.py
used for?
__init__.py
file is a special file in Python that serves several purposes such as package initialisation, import control, and package level code. Marks a directory as a Python package. You can also create namespace packages without it in Python 3.3 version. But here's the catch: this file is widely used and supported.
Q18. What is a lambda function?
A lambda function in Python is a small, anonymous function defined using the lambda
keyword. It can have any number of arguments, but only one expression, which is evaluated and returned automatically. It is mostly used in cases like data processing, event handling, and sorting. Here's an example -
# Lambda function to square a number
square = lambda x: x * x
print(square(5)) # Output: 25
Q19. How is a for loop different from a while loop?for
is used for iteration, while
is used when the end condition is unknown. Both these are used for iteration, but they differ in their syntax and use cases. So for is to loop over items or fixed range and while when oop while condition is true.
Q20. What is the purpose of pass
?
the pass
statement is used as a placeholder. It does nothing when executed and is typically used when a statement is syntactically required, but you don’t want to execute any code yet. It has many purposes such as defining empty functions, classes, or loops while working on the logic, help in avoiding syntax errors when a block is required but not yet implemented.
Q21.What is the purpose of id()
function in Python?
The id()
function in Python returns the unique identifier for an object. This identifier is a unique integer (or long integer in Python 2) that's guaranteed to be unique and constant for an object during its lifetime. This can be used in checking Object Identity and debugging.
Q22. What is a list comprehension?
A list comprehension is a compact way to create a new list from an existing iterable by applying a transformation or filter to each element. It's a concise and expressive syntax that combines the functionality of a for
loop and an if
statement. You can write more efficient, readable, and Pythonic code by using list comprehension.
Q23. What is slicing in Python?
Slicing is a technique in Python used to extract a portion of a list, string, tuple, or other iterable by specifying a start, stop, and optional step.
Syntax:
sequence[start:stop:step]
- start: Index to begin slice (inclusive)
- stop: Index to end slice (exclusive)
- step: Interval between elements (optional)
Example:
text = "Python"
print(text[1:4]) # Output: 'yth'
print(text[::-1]) # Output: 'nohtyP' (reversed)
Q24. How to read/write files in Python?
Python provides built-in functions to read from and write to files using the open()
function.
Reading a File:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Here, 'r'
= read mode and with
automatically closes the file after use.
Writing to a File:
with open('example.txt', 'w') as file:
file.write("Hello, world!")
'w'
= write mode (overwrites file) and use 'a'
for append mode (adds to the file).Reading Line-by-Line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
Q25. What are escape characters in strings?
Escape characters in Python are special characters preceded by a backslash (\
) that allow you to insert characters that are otherwise hard to type or have special meaning in strings. Common escape characters are :
Characters | Meaning |
\n | New line |
\t | Tab |
\\ | Backslash (\ ) |
\' | Single quote (' ) |
\" | Double quote (" ) |
\r | Carriage return |
\b | Backspace |
Example:
print("Hello\nWorld") # Output:
# Hello
# World
print("She said, \"Hello!\"") # Output: She said, "Hello!"
Q26. What is the difference between append()
and extend()
?
append()
and extend()
are two methods used to add elements to a list in Python. The key difference between them is that append()
adds a single element to the end of the list. If you pass a list as an argument, it will be added as a single element (a nested list). while extend()
adds multiple elements to the end of the list. If you pass a list as an argument, its elements will be added individually to the list.
Q27. How do you reverse a list?
You can reverse a list using several methods:
Method 1: Using reverse()
(in-place)
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
my_list = [1, 2, 3, 4]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [4, 3, 2, 1]
reversed()
(returns an iterator)my_list = [1, 2, 3, 4]
print(list(reversed(my_list))) # Output: [4, 3, 2, 1]
reverse()
to modify the original list, or use slicing or reversed()
if you want a new reversed list.Q28. What is None
in Python?
None
is a special constant in Python that represents the absence of a value or a null value. The key points are: it is of the nonetype
data type. it is commonly used to indicate no return from a function or a default placeholder. Example:
def say_hello():
print("Hello")
result = say_hello()
print(result) # Output: None
result
holds None
.Q29. What are Python's logical operators?
Python's logical operators are used to combine conditional statements. There are three logical operators: and,
or
, not
. In and
it returns True if both conditions are true. Inor
: it returns True if at least one condition is true. in not
it returns the opposite of the condition.
Q30. What are identity operators?
Identity operators in Python are used to check if two variables refer to the same object in memory. There are two identity operators: is
and is not
.
is
: Returns True if both variables refer to the same object and is not
: Returns True if both variables do not refer to the same object.
Q31. What is a set in Python?
A set in Python is an unordered collection of unique elements. Sets are used to store multiple items in a single variable, and they are particularly useful when you need to perform mathematical operations like union, intersection, and difference.
Q32. How do you install packages in Python?
You can install packages using pip
, Python’s package manager.
Command:
pip install package_name
pip install requests
requests
library, which helps you make HTTP requests in Python.Make sure pip is installed and updated by running:
python -m pip install --upgrade pip
Q33. How do you import a specific function from a module?
You can import a specific function using this syntax:
from module_name import function_name
from math import sqrt
print(sqrt(16)) # Output: 4.0
sqrt()
directly without prefixing it with math.
.Q34. What is the difference between break and continue?
The break and continue are two control flow statements in Python that are used to manipulate the flow of loops. Break terminates the loop entirely, skipping any remaining iterations, whereas continue skips the current iteration and moves on to the next iteration of the loop.
Q35. What is a class in Python?
A class method is a method that takes cls
as the first parameter and operates on the class rather than the instance. A class method have full access to its class variables. It can also be used to create a constructor.
@classmethod
def from_year(cls, year):
return cls(year)
Q36. What is an object in Python?
An object is an instance of a class. It encapsulates data and behavior defined by the class. Objects represents the real world entities or abstract concepts that can be manipulated and interacted with in a program.
my_cat = cat("kitty")
Q37. How do you define a constructor in Python?
A constructor is defined using the __init__()
method. It automatically runs when an object of a class is created, allowing you to initialize object attributes. Example:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(p.name) # Output: Alice
Here, The __init__
method sets up the object with initial values.
Q38. What is inheritance?
Inheritance in Python is a fundamental concepts in OOPs that have the process of one class to inherit the attributes and methods of another. The inheriting is called subclass
or derived class
while the class being inherited from is called superclass
or based class.
Q39. What is polymorphism?
Polymorphism in Python is a core concept in OOPs that allows different classes to define methods with the same name that behave differently. There are three types of polymorphism: method overriding, method overloading, and function polymorphism.
Q40. What are docstrings
in Python?
Docstrings in Python are strings that are used to document modules, functions, classes, and methods. They provide a way to describe the purpose, behavior, and usage of code, making it easier for others (and yourself) to understand how to use it.
Q41. What are iterators in Python?
Iterators in Python are objects with__iter__()
and__next__()
methods. that allow you to iterate over a sequence (like a list, tuple, or string) or other iterable objects. They provide a way to access the elements of an object one at a time, without having to load the entire object into memory.
Q42. What are generators?
Generators in Python are a type of iterable, similar to lists or tuples, but they don't store all the values in memory at once. Instead, generators compute their values on the fly, which can be useful for large datasets or complex computations. You can use for handling Large Datasets, Improving Performance, and Creating Iterators.
Q43. What is a decorator?
Decorators in Python are a powerful feature that allows developers to modify or extend the behavior of a function or class without changing its source code. They are essentially wrappers that add additional functionality to an existing function or class. Example:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
my_decorator
function is a decorator that adds behaviour before and after the say_hello
function is called. The @my_decorator
syntax above the say_hello
function definition applies the decorator to the function.Q44. What is a context manager?
A context manager is a Python object that properly manages resources by setting things up before a block of code runs and cleaning up afterward — especially useful for files, database connections, or network sockets. It uses the with
statement to ensure resources are automatically released, even if an error occurs.
Used with with
statement:
with open('file.txt') as f:
data = f.read()
# File is automatically closed
Q45. What is @property
in Python?
The @property decorator in Python is used to implement getter and setter methods for instance attributes. It allows you to define custom accessors for attributes, enabling more control over how attributes are accessed and modified.
Q46. What is the difference between shallow and deep copy?
when you assign an object in Python to a new variable, it doesn't create a new object but rather a reference to the original object. To create a new object that's a copy of the original, you can use either shallow copy or a deep copy. Shallow copy creates a new object and then (to the extent possible) inserts references into it to the objects found in the original, whereas Deep copy creates a new object and then, recursively, inserts copies into it of the objects found in the original.
Q47. How does Python manage memory?
Python manages memory using a combination of automatic memory management techniques, which include: reference counting, garbage collection, private heap space, and memory pools via PyMalloc. These are mainly used to to efficiently manage memory and reduce leaks.
Q48. What are Python's built-in data structures?
Python has several built-in data structures that can be used to store and manipulate data. The data structures are Lists, Tuples, Dictionaries, Sets, and Frozensets. You can write more efficient and effective code by understanding Python's built in data structures.
Q49. What is duck typing in Python?
Duck typing is a concept in Python where the type or class of an object is less important than the methods or behaviours it defines. This approach is based on the idea that "if it walks like a duck and quacks like a duck, then it's a duck."If an object behaves like a duck (implements needed methods), it's treated as such, regardless of its actual class.
Q50. What are magic methods?
Magic methods, also known as dunder
methods (short for double underscore), are special methods in Python classes that are surrounded by double underscores (__)
on both sides of the method name. These methods are used to define custom behaviour for operators, functions, and other built-in operations..You can use special methods with double underscores like __str__
, __add__
.
Q51. What is the difference between isinstance()
and type()
?
isinstance()
and type()
are two different ways to check the type of an object. However, they have distinct behaviors and use cases.type()
checks if the type of an object matches exactly with the specified type whereas isinstance()
checks if an object is an instance of a class or its subclass.
Q52. What is the purpose of super()
?
The key purposes of super() are method Overriding, method Extension, and accessing Parent Class Attributes. You can write more flexible and maintainable code that takes advantage of inheritance and method overriding by using super().
Q53. What is the difference between classmethod
, staticmethod
, and instance method?
Methods can be defined as instance methods
, class methods
, or static methods
. Each type of method has its own use case and characteristics.
Instance methods are bound to an instance of a class and have access to the instance's attributes, while Class methods are bound to a class and have access to the class's attributes and Static methods are not bound to a class or instance and do not have access to class or instance attributes.
Q54. What is metaclass in Python?
A metaclass is a class that creates classes. Metaclasses are used to define the behaviour of classes, such as how they are initialised, how their attributes are accessed, and how they are instantiated. Here's a by default example that uses the built-in type
as the metaclass for all classes.
# Define a metaclass
class MyMeta(type):
def __new__(cls, name, bases, dct):
dct['greet'] = lambda self: f"Hello from {self.__class__.__name__}"
return super().__new__(cls, name, bases, dct)
# Use the metaclass in a class
class MyClass(metaclass=MyMeta):
pass
obj = MyClass()
print(obj.greet()) # Output: Hello from MyClass
Q55. What is method overloading?
Method overriding in Python allows a child class to provide a specific implementation of a method that is already defined in its parent class. That means redefining a method in a child class already defined in the parent class. The overridden method in the child class replaces the parent class method when called through the child class instance.
Q56. How does Python support multiple inheritance?
Python supports multiple inheritance, which allows a class to inherit properties and methods from multiple parent classes. This feature enables code reuse and facilitates the creation of complex class hierarchies via MRO (Method Resolution Order), based on C3 linearization.
Q57. What is the importance of pass
statement in python?
The pass statement in Python is a placeholder when a statement is required syntactically, but no execution of code is necessary. The importance of pass
statement lies in the placeholder, code structure, and future implementation.
Q58. What is monkey patching?
Monkey patching is a way to extend or modify the runtime behavior of a module or class in Python without modifying its source code. It allows you to replace or add methods or attributes to an existing class or module at runtime.
Q59. What are coroutines?
Coroutines are a fundamental concept in asynchronous programming in Python. They allow you to write single-threaded concurrent code that can handle multiple tasks simultaneously. Special generators that can consume values using send()
. This can Improve Responsiveness, utilise Efficient resources:, and simplify Code.
Q60. What is __slots__
?
__slots__
is a special attribute in Python classes that allows you to explicitly declare the data attributes (instance variables) of a class. You can improve memory efficiency, prevent dynamic attribute creation by using _slots_. Here's an Syntax example :
class Person:
__slots__ = ['name', 'age'] # Only these attributes allowed
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('Alice', 30)
print(p.name) # Output: Alice
p.height = 170 # Raises AttributeError: 'Person' object has no attribute 'height'
, __slots__
helps optimize memory and control what attributes instances can have.Q61. What are type hints in Python?
Type hints are a feature in Python that allows you to specify the expected types of variables, function parameters, and return values. They are used to improve code readability, facilitate static type checking, and enable better code completion in IDEs. You can use syntax to indicate variable types using def func(x: int) -> str:
.
Q62. How do you enforce data hiding in Python?
Data hiding is enforced using naming conventions rather than strict access modifiers like in other languages.
Here are some techniques:
Single Underscore (_var
):
class Person:
def __init__(self, name):
self._name = name # Protected
- Indicates a protected member (a hint to developers not to access it directly).
__var
)class Person:
def __init__(self, name):
self.__name = name # Private
p = Person("Alice")
print(p._Person__name) # Access via name mangling
- Triggers name mangling, making it harder to access from outside.
Q63. What is a frozen set?
A frozen set is an immutable set in Python, which means its contents cannot be modified after creation. Frozen sets are similar to sets, but they are immutable, making them hashable and suitable for use in sets and dictionaries.
Q64. What is collections.namedtuple
?
namedtuple
is a factory function in Python's collections
module that returns a tuple subclass with named fields, making your code more readable and self-documenting. You can use it to combine the immutability and performance of a tuple with the readability of attribute access, and also use it when you want to create lightweight, immutable objects without writing a full class. Exxample:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x) # Output: 10
print(p.y) # Output: 20
p[0]
, you can use p.x
, making your code easier to understand.Q65. What is a weak reference?
A weak reference is a reference to an object that does not increase the object's reference count. This allows the object to be garbage collected if there are no strong references to it.
Q66. What is a memory view object?
A memory view object is a buffer interface that allows you to access the internal data of an object that supports the buffer protocol, such as arrays or bytes. Memory views provide a way to work with binary data without copying it, which can be efficient for large datasets. You can work efficiently with binary data in Python by understanding memory view objects.
If you are struggling with bit level
Q67. What are map()
, filter()
, and reduce()
?
map()
, filter()
, and reduce()
are three fundamental functions in Python that allow you to process and transform data in a functional programming style. They can help you process and transform data efficiently. Here's a code example of each functions:
map()
Applies a function to each item in an iterable and returns a new iterable.
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
filter()
Filters elements based on a condition (function that returns True/False).
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # Output: [2, 4]
reduce()
Performs a rolling computation to reduce a sequence to a single value.
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10
(Needs to be imported from functools
)
Q68. What is the use of zip()
?
The zip() function is a built-in Python function that takes iterables (such as lists, tuples, or strings) as input and returns an iterator of tuples. Each tuple contains one element from each of the input iterables, in order. It is mainly used in cases like pairing Data, Iterating Over multiple Lists, creating dictionaries. Example:
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 95]
combined = zip(names, scores)
print(list(combined))
[('Alice', 85), ('Bob', 90), ('Charlie', 95)]
Q69. What is a command-line argument in Python?
Command-line arguments are values passed to a Python script or program when it is executed from the command line. These arguments can be used to customise the behaviour of the script or provide input data.
You can access command-line arguments using the sys
module’s argv
list. Example:
import sys
# sys.argv[0] is the script name
# sys.argv[1] is the first argument passed
print("Script name:", sys.argv[0])
print("First argument:", sys.argv[1])
python script.py hello
Script name: script.py
First argument: hello
Q70. How do you handle JSON in Python?
Python provides the json
module to handle JSON (JavaScript Object Notation) data. JSON is a lightweight data interchange format that is easy to read and write. Here's a short example of handling JSON using the built-in json
module.
import json
# Convert Python to JSON
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
# Convert JSON to Python
parsed_data = json.loads(json_str)
Q71. What is pickling in Python?
Pickling is a process in Python where Python objects are converted into a byte stream. This byte stream can be stored in a file or database, or transmitted over a network. The pickled object can be reconstructed later, preserving its original state and structure. There are some main features of pickling: Serialisation, Deserialization, and Object Reconstruction.
Q72. What is the difference between str()
and repr()
?
str()
and repr()
are two built in functions that convert objects to strings. While both functions return a string representation of an object, they serve different purposes and have distinct behaviors. str()
is used for human-readable output, while repr()
is used for debugging, logging, and object recreation. - str()
output is often more readable, whereas repr()
output is more precise and formal.
Q73. What is a singleton class?
A singleton class is a design pattern that restricts a class from instantiating multiple objects. It ensures that only one instance of the class exists, and provides a global point of access to that instance. Example of a singleton class in python:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
# Usage
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # Output: True (both refer to the same instance)
Q74. How do you manage package dependencies in Python?
Python provides several tools and techniques to manage package dependencies, ensuring that your projects are reproducible, maintainable, and scalable. There are key tools such as pip: pip
and requirements.txt: requirements.txt. You can effectively manage package dependencies in your Python projects using requirements.txt
and virtual environments.
Q75. What is the difference between mutable and immutable types?
Objects in Python can be classified into two categories: mutable and immutable. The key difference in these two types lies in their ability to be modified after creation.
he primary difference between mutable and immutable types is their modifiability. Mutable objects can be changed, while immutable objects cannot. Immutable objects are hashable, meaning they can be used as keys in dictionaries. Mutable objects are not hashable.
Q76. What is the Global Interpreter Lock (GIL)?
The Global Interpreter Lock (GIL) is a mutex mechanism used in CPython, the standard implementation of the Python programming language, that allows only one thread to execute Python bytecode at a time, affecting multithreaded performance.
Q77. How does Python’s garbage collector detect cycles?
Python's garbage collector is a mechanism that automatically frees up memory occupied by objects that are no longer needed or referenced. It uses a combination of reference counting and cycle detection to identify objects that can be safely deleted. Here's a example of reference cycle:
import gc
class Node:
def __init__(self):
self.ref = None
a = Node()
b = Node()
a.ref = b
b.ref = a # Cycle: a <-> b
del a
del b
gc.collect() # Forces garbage collection of the cycle
To inspect or debug cycles:
import gc
gc.set_debug(gc.DEBUG_LEAK)
Q78. What is the difference between threading and multiprocessing?
The basic difference between threading and multiprocessing is that threading involves creating multiple threads within a single process, whereas multiprocessing involves creating multiple processes, each with its own memory space. Threading uses a shared-memory concurrency model, while multiprocessing uses a separate-memory concurrency model.
Q79. How do you implement custom exceptions?
In Python, you can implement custom exceptions by creating a new class that inherits from the built-in Exception
class. This allows you to create clearer, more specific error messages tailored to your application's logic. You can improve yourcode readability, help in fine-grained error handling, and Make debugging and logging easier with descriptive error messages. Here's a basic syntax example:
class MyCustomError(Exception):
pass
# Using the custom exception
def divide(a, b):
if b == 0:
raise MyCustomError("Cannot divide by zero!")
return a / b
Q80. What is an abstract base class?
An abstract base class is a class with one or more abstract methods using abc
module. You can use it to ensure consistency across subclasses, prevent the instantiation of incomplete classes, and promote code reusability and design clarity. For example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
Animal
directly, but Dog
must implement the make_sound
method.Q81. What are asynchronous functions in Python?
An asynchronous function is defined using the async def
syntax and is designed to be paused and resumed using the await
keyword. You can use it to Improve performance for I/O-heavy applications and enable concurrency without using threads or processes. Example:
import asyncio
async def fetch_data():
print("Start fetching")
await asyncio.sleep(2)
print("Done fetching")
asyncio.run(fetch_data())
Q82. How do you use asyncio
?
asyncio
is a built-in Python library that allows you to write single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, and implementing network clients and servers. You can useasync/await
to define an asynchronous function and thenawait
to pause the function until an async task completes. Finally, Run your async code with asyncio.run()
or an event loop. Here's a simple example-
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # Non-blocking wait for 1 second
print("World")
asyncio.run(say_hello())
If you want to dive deeper, check out this Python Celery Tutorial with Django to learn how async task queues use async programming in real projects!
Q83. What is __name__ == "__main__"
used for?
The __name__ == "__main__"
construct is used to determine whether a Python script is being run directly or being imported as a module. When you run a Python file directly, Python sets the special variable __name__
to "__main__"
. If the file is imported into another script, __name__
is set to the module’s name instead. This lets youcontrol what code runs only when the script is executed directly, not when it’s imported. For example:
def greet():
print("Hello!")
if __name__ == "__main__":
greet() # This runs only if the script is executed directly
So, it helps you write reusable modules that can also act as standalone programs!
Q84. What are metaprogramming techniques in Python?
Metaprogramming is a programming technique where a program generates, manipulates, or modifies other programs or its own code at runtime. It lets you create flexible, reusable, and dynamic programs. There are common metaprogramming techniques in python, such as using type()
to create classes dynamically, __getattr__
, __setattr__
methods to customize attribute access, and exec()
&eval()
to execute dynamically generated code.
Q85. What is a memory leak and how to avoid it?
Memory leak happens when a program unintentionally keeps references to objects that are no longer needed, preventing Python’s garbage collector from freeing that memory. Over time, this causes increased memory usage and can slow down or crash the program. Just a heads up, you can remove unnecessary references, avoid circular references, and use weak references to avoid memory leaks.
Q86. How do you create a thread-safe class in Python?
First you need to ensure that the class's methods and attributes are accessed in a way that prevents concurrent modification or access by multiple threads before creating a thread-safe class python. You can create a thread-safe class using threading.Lock()
to prevent race conditions. For example:
import threading
class Counter:
def __init__(self):
self.count = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.count += 1
def get_count(self):
with self.lock:
return self.count
threading.Lock()
ensures that only one thread can access the critical section at a time and with self.lock:
block automatically acquires and releases the lock. This makes the Counter
class safe for use across multiple threads.Q87. What are the uses of functools
module?
The functools module in Python provides functions for managing and manipulating functions. It includes tools for function composition, caching, and partial application. The functionalities of this module are partial
, reduce
, singledispatch
, and lru_cache.
Q88. What is method chaining in Python?
Method chaining is a programming technique in Python where multiple methods are called on an object in a single statement. Each method returns the object itself, allowing the next method to be called on the same object. The main features of chaining in Python are concise code and improved readability.
Q89. What is the difference between compile-time and runtime?
the terms "compile-time"
and "runtime
" in Python refer to different stages of a program's lifecycle. At compile-time, the system translates the source code into machine code or an intermediate form that the computer can execute. The compiler typically catches errors during this stage. At runtime, the system executes the compiled program. The program itself or the runtime environment handles any errors that occur during execution.
Q90. What are the differences between Python 2 and Python 3?
Python 2 and Python 3 are two major versions of the Python programming language. While both versions share many similarities, there are significant differences between them. such as In Python 2, print
is a statement, while in Python 3, it's a function, the /
operator in python 2 performs integer division when both operands are integers, but in Python 3, the / operator always performs floating-point division.
Q91. What are descriptors in Python?
Descriptors are a protocol in Python that allows objects that define using these methods: __get__
, __set__
, and __delete _
to implement attribute access, modification, and deletion for other objects. They’re the foundation of properties, methods, and static/class methods. Example:
class Descriptor:
def __get__(self, instance, owner):
return "Got it!"
class MyClass:
attr = Descriptor()
obj = MyClass()
print(obj.attr) # Output: Got it!
Q92. What is the role of __call__
method?
The __call__ method is a special method in Python that allows an instance of a class to be called as a function. This method is invoked when an instance is used as a callable. The key features of this method are callable instances and customizable behaviour. This method is usually used in cases like Function-like objects, Custom decorators, and Callback systems.
Q93. What is a metaclass
hook?
Metaclass
hooks are special methods that can be defined in a metaclass
to customize the creation and behaviour of classes. These hooks allow you to intercept and modify the class creation process, enabling advanced customization and automation. Here are two common metaclass
hook : __new__:
and __init__
. For example:
class Meta(type):
def __new__(cls, name, bases, namespace):
print(f"Creating class {name}")
return type.__new__(cls, name, bases, namespace)
class MyClass(metaclass=Meta):
pass
Meta
metaclass defines a __new__
method that prints a message when a class is created. The MyClass
class uses the Meta
metaclass, so the message is printed when MyClass
is defined.Q94. What are contextvars?
Context variables are a way to manage context specific state in Python, allowing maintenance of context in async applications. You can improve your code organisation and reduce complexity by using it.
Q95. How do you test Python code?
Testing is an essential part of the software development process that ensures your code works as expected and catches bugs early. You can test your code using this testing framework and tool: unittest
, pytest
, or doctest
. You can ensure the calculate_area
function behaves correctly and catches any potential bugs by writing tests. Here's an example of python code test using unittest :
import unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Q96. What is __dict__
attribute?
The __dict__
attribute is a built-in dictionary that stores an object’s (writable) attributes. It lets you inspect or modify attributes dynamically. It is usually used in cases like debugging, sterilisation, and dynamic attribute manipulation.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.__dict__)
{'name': 'Alice', 'age': 30}
You can better appreciate Python's object model and leverage its dynamic attribute access capabilities effectively by understanding the dict
attribute.
Q97. How do you profile Python code?
Profiling Python code involves analysing its performance to identify bottlenecks and areas for optimisation. You can profile Python code using built-in modules like cProfile
, profile
, or third-party tools like line_profiler
. These tools help identify bottlenecks by measuring execution time of functions.
import cProfile
cProfile.run('your_function()')
snakeviz
or line_profiler
for more visual and detailed analysis when optimizing performance-critical Python applications.Q98. How do you handle circular imports?
Circular imports occur when two or more modules depend on each other by refactoring or using lazy imports. Here are some strategies to handle circular imports: Refactor code, use import statements wisely, dependency injection, and lazy imports. You can minimize the impact of circular imports and write more maintainable, efficient code by using these strategies.
Q99. What is the difference between Python compiled .pyc
and .py
?
.py
file in Python contains the source code you write while, .pyc
files contain the compiled bytecode that's executed by the Python virtual machine (PVM). Here's a another source that.pyc
files are platform-independent, meaning they can be executed on any platform that has a Python interpreter.
Q100. How is Python interpreted?
Python is a interpreted language which means that the code is executed line by line by a interpreted at runtime. Here's a short process of python interpreted: Source code → Bytecode → Interpreted by Python VM.
Bonus Tip for Freshers
If you are just starting out with python language and now preparing for job interviews, then here's a bonus tip for you :
When you feel stuck somewhere during interview, highlight your problem solving approach, showcase your interest in python, demonstrate your ability to learn.
You can easily make a good impression to the interviewer by showing your enthusiasm, interest, and learning oriented attitude.
Conclusion
Python's simplicity and versatility make it a favourite language among the freshers and experienced developers. Whether you are a beginner or diving deeper into python, these Q&As are enough to make you crack a successful job in tech .
I have addressed questions and answers that can possibly come into a python interview.
If you find any mistake or think any improvements needed, comment below to let me know for better answers!