Python Interview Questions
Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.
What is the difference between deep and shallow copying of an object in Python?
Shallow copying creates and populates a new object referencing the original object's data. Suppose the original object contains mutable objects as elements. In that case, the new entity will reference the same mutable objects, and changes to the mutable objects are reflected in both the new and original objects.
Deep copying creates a new object and recursively copies the original object's data and the data of any things it references. It means that the new entity and its simulated data are entirely independent of the original object and its data.
What are the generators in Python?
Functions that return an iterable set of items are called generators.
Generators are functions that return iterable collection of items, one at a time, in a fixed manner. Generators, generally, are used to create iterators with a different approach. They employ the use of yield keywords rather than return to return a generator object.
Let's try and build a generator for Factorials of numbers
## generate factorials of numbers up to n
def factorial(n):
i = 1
fact = i
while(i < n):
fact *= i
yield fact
i += 1
a = factorial(8) # create generator object
## iterating using __next__(), for Python2, use next()
a.__next__() # output => 1
a.__next__() # output => 2
a.__next__() # output => 6
a.__next__() # output => 24
a.__next__() # output => 120
a.__next__() # output => 720
a.__next__() # output => 5040
a.__next__() # error
## iterating using loop
for i in factorial(10):
print(i) # output => 1 2 6 24 120 720 5040 40320 362880 3628800
What is the difference between a function and a method in Python?
In Python, a function is a block of code that performs a task and is defined using the def keyword. It can be used on its own, outside of any class.
For example-
def add(a, b):
return a + b
A method, on the other hand, is a function that is associated with an object. Methods are defined inside classes and are called using dot notation.
For example-
name = "Alice"
print(name.upper()) # upper() is a method
Conclusion: All methods are functions, but not all functions are methods. Methods always belong to an object or class, while functions do not.
What is the difference between Python Arrays and lists?
- Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
- Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.
Is Python a compiled language or an interpreted language?
Please remember one thing, whether a language is compiled or interpreted or both is not defined in the language standard. In other words, it is not a properly of a programming language. Different Python distributions (or implementations) choose to do different things (compile or interpret or both). However the most common implementations like CPython do both compile and interpret, but in different stages of its execution process.
- Compilation: When you write Python code and run it, the source code (.py files) is first compiled into an intermediate form called bytecode (.pyc files). This bytecode is a lower-level representation of your code, but it is still not directly machine code. It’s something that the Python Virtual Machine (PVM) can understand and execute.
- Interpretation: After Python code is compiled into bytecode, it is executed by the Python Virtual Machine (PVM), which is an interpreter. The PVM reads the bytecode and executes it line-by-line at runtime, which is why Python is considered an interpreted language in practice.
Write a Python factorial program without using if-else, for, and ternary operators.
We can use a recursive function that calculates the factorial of a given number without using if-else, for, and ternary operators:
The function recursively calls itself until it reaches the base case of n=1, at which point it returns 1. Each recursive call multiplies the current value of n by the result of the previous call, effectively calculating the factorial.
def factorial(n):
return (n == 1) or (n * factorial(n - 1))
print(factorial(4)) # Output: 24
What are Pickling and Unpickling?
Pickling and unpickling are processes used in Python to serialize and deserialize objects. Serialization converts an object into a byte stream, which can be stored or transmitted over a network. Deserialization transforms a sequence of bytes, typically stored in a file or transmitted over a network, back into an object in memory that can be manipulated and used by a program.
- Pickling converts a Python object hierarchy into a byte stream using the pickle module. This byte stream can be saved to a file or sent over a network. The pickle module can handle most Python objects, including complex data types such as lists, sets, and dictionaries.
- Unpickling is the reverse process of pickling. It involves reading a byte stream and reconstructing the original Python object hierarchy. This is done using the pickle.load() function.
What is the time-complexity of appending to a Python list?
What are iterators in Python? How to create a custom iterator using a class
In Python, an iterator is an object that implements the iterator protocol, which consists of two methods:
__iter__()
: Returns the iterator object itself.__next__()
: Returns the next value from the sequence. If there are no further items, it should raiseStopIteration
.
All built-in collections like lists, tuples, and dictionaries are iterable. You can loop through them using a for
loop.
Creating a Custom Iterator:
You can create a custom iterator using a class by defining the __iter__
and __next__
methods.
class CountDown:
def __init__(self, start):
self.num = start
def __iter__(self):
return self
def __next__(self):
if self.num <= 0:
raise StopIteration
current = self.num
self.num -= 1
return current
# Using the iterator
for number in CountDown(5):
print(number)
This will output: 5, 4, 3, 2, 1.
Custom iterators give you full control over how values are produced and iterated in loops.
What are modules and packages in Python?
Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages -
- Simplicity: Working on single modules helps you focus on a relatively small portion of the existing problem. This makes development more manageable and less prone to errors.
- Maintainability: Modules are designed to enforce the logical boundaries between different problem domains. If they are written to reduce interdependency, it is less likely that the modifications in a module might also impact other parts of the program.
- Reusability: Functions defined in a module can easily be reused by the other parts of the application.
- Scoping Modules are typically defined as separate namespaces, which help avoid confusion between identifiers from other aspects of the program
Modules are simply Python files with a '.py' extension and can have a set of functions, classes and variables defined. They can be imported and initialised using import statements if partial functionality is required to import the requisite classes or processes, such as the foo import bar.
Packages provide for hierarchical structuring of the module namespace using a '.' dot notation. As modules help avoid clashes between global and local variable names, similarly, packages can help prevent conflicts between module names.
Creating a package is easy since it also uses the system's inherent file structure that exists. Modules combined into a folder are known as packages. Importing a module or its contents from a package requires the package name as a prefix to the module's name joined by a dot.
How do you initialise an empty class in Python?
An empty class does not have any members defined inside it. It is created using the pass
keyword (the pass command does nothing in Python). We can make all the objects for this class outside the class.
For example-
class EmptyClass:
pass
obj = EmptyClass()
obj.name = "Arun"
print("Name created = ", obj.name) # Output: Name created = Arun
Does Python support multiple inheritance? How does it work in Python? Explain with an example.
Yes, Python supports multiple inheritance. A class can inherit from more than one parent class, combining their behavior. Python uses a method resolution order (MRO) to determine which method to invoke when there are conflicts.
Example of Multiple Inheritance:
class Father:
def skills(self):
print("Father: Gardening, Programming")
class Mother:
def skills(self):
print("Mother: Cooking, Painting")
class Child(Father, Mother):
def skills(self):
print("Child inherits skills from both parents")
Father.skills(self)
Mother.skills(self)
c = Child()
c.skills()
Output:
Child inherits skills from both parents Father: Gardening, Programming Mother: Cooking, Painting
Method Resolution Order (MRO):
If methods are named the same in both parents, Python resolves the call using the MRO (left-to-right order):
class A:
def show(self):
print("A")
class B:
def show(self):
print("B")
class C(A, B):
pass
c = C()
c.show() # Output: A
What is the difference between del and remove() in Python?
In Python, both del
and remove()
are used to delete elements, but they operate differently and are used in different contexts.
- The
del
statement is a language construct used to delete an item at a specific index from a list or to delete entire variables or slices. It works with all types of objects, including lists, dictionaries, and variables.
For example:
nums = [1, 2, 3, 4]
del nums[1] # Removes the item at index 1 (value 2)
- The
remove()
method, on the other hand, is a list method that removes the first occurrence of a specific value from the list. It raises a ValueError if the item is not found
For example:
nums = [1, 2, 3, 2]
nums.remove(2) # Removes the first 2
In summary, use del
when you know the index or want to delete a variable. Use remove()
when you want to delete a known value from a list.
What is a higher-order function in Python?
A higher-order function is any function that either:
- Accepts another function as an argument, or
- Returns a function as its result.
Python supports higher-order functions natively, making it flexible for functional-style programming.
Common Higher-Order Functions:
map()
filter()
sorted()
Example:
def apply_twice(func, value):
return func(func(value))
def square(x):
return x * x
print(apply_twice(square, 2)) # Output: 16
Higher-order functions promote reusability and abstraction, enabling more expressive and concise code.
How do you handle exceptions in Python?
In Python, you handle errors and exceptions using try
, except
, and optionally finally
. This allows your program to continue running even if something goes wrong.
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number.")
finally:
print("This always runs.")
The try
block runs the risky code. If there’s an error, Python checks for a matching except
block. The finally
block always runs, whether an error occurred or not.
Exception handling makes your programs more robust and user-friendly.
Why Choose Our Question Bank?
Get access to expertly crafted answers and comprehensive preparation materials
Complete Collection
Access all 15 carefully curated questions covering every aspect of Python interviews
Expert Answers
Get detailed, professional answers crafted by industry experts with real-world experience
Instant Access
Start preparing immediately with instant access to all questions and answers after sign-up