Python Interview Questions – Part 1
- November 13, 2022
- Posted by: Code and Debug
- Category: Interview Questions Python

In this blog, you will get the interview questions and answers to test your knowledge in Python and help you crack interviews.
1) What are the types of inheritance in Python?
Python supports different types of inheritance, they are:
- Single Inheritance
- Multi-level Inheritance
- Hierarchical Inheritance
- Multiple Inheritance
2) What is the difference between a module, a package, and a library?
A module is simply a Python file that’s intended to be imported into scripts or other modules. It contains functions, classes, and global variables.
A package is a collection of modules that are grouped together inside a folder to provide consistent functionality. Packages can be imported just like modules. They usually have an __init__.pyfile in them that tells the Python interpreter to process them as such.
A library is a collection of packages.
3) What are decorators? Can you describe a situation in which decorators are worth using?
A decorator is a function that receives a function as input and returns a function as output. The goal of a decorator is to extend the behavior of the input function without changing its core mechanism.
Using a decorator also prevents you from repeating yourself. It forces you to write a generic code once and then tap it to every function that needs it.
In fact, any object which implements the special __call__() method is termed callable. So, in the most basic sense, a decorator is a callable that returns a callable.
Basically, a decorator takes in a function, adds some functionality and returns it.
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
When you run the following codes in shell,
>>> ordinary()
I am ordinary
>>> # let's decorate this ordinary function
>>> pretty = make_pretty(ordinary)
>>> pretty()
I got decorated
I am ordinary
In the example shown above, make_pretty() is a decorator. In the assignment step:
pretty = make_pretty(ordinary)
The function ordinary() got decorated and the returned function was given the name pretty.
We can see that the decorator function added some new functionality to the original function. This is similar to packing a gift. The decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. But now, it looks pretty (since it got decorated).
Generally, we decorate a function and reassign it as,
ordinary = make_pretty(ordinary).
This is a common construct and for this reason, Python has a syntax to simplify this.
We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be decorated. For example,
@make_pretty
def ordinary():
print("I am ordinary")
is equivalent to
def ordinary():
print("I am ordinary")
ordinary = make_pretty(ordinary)
4) What are docstrings in Python?
Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
"""
Using docstring as a comment.
This program divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)
5) How can the ternary operators be used in python?
The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.
age=int(input("Enter your age = "))
print("You are a adult") if age > 18 else print("You are a child")
6) What does this mean: *args, **kwargs? And why would we use it?
We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments.
7) Are function arguments passed by reference or by value?
All function arguments are passed by reference in Python: this means that if you pass a parameter to a function, the function gets a reference to that same object.
If the object is mutable and the function changes it, the parameter will mutate in the outer scope of the function. Let’s see an example:
def appendInList(mylist,number):
mylist.append(number)
a=[1,2,3,4]
appendInList(a,5)
print(a)
8) What is the difference between a class method and a static method? When should you use which?
A static method is a method that knows anything about the class or the instance that had called it. It’s a method that logically belongs to the class but doesn’t have implicit arguments.
A static method can be either called on the class or any of its instances.
A class method is a method that gets passed the class it was called on, much like self is passed to other instance methods in a class. The mandatory argument of a class method isn’t a class instance: it’s actually the class itself.
A typical use-case of class methods is providing an alternative way to construct instances: a class method that does this is known as a factory of the class.
Here’s an Employee class that uses a class method that creates an instance in a slightly different way than the main constructor of the class.
class Employee(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def from_string(cls, name_str):
first_name, last_name = map(str, name_str.split(' '))
employee = cls(first_name, last_name)
return employee
anirudh = Employee.from_string('Anirudh Khurana')
9) How to prevent a function from being called an unnecessary amount of time?
If the output that is associated with a given input doesn’t change over a period of time, using caching would make sense for the function.
A typical scenario would be querying a web server: if you query a URL the first time and you know that response won’t change, you can cache the result.
from cachetools import cached, TTLCache
cache = TTLCache(maxsize=100, ttl=86400)
@cached(cache)
def extract_article_content(url):
response = requests.get(url)
content = response.content
return content
10) What is the process of compilation and linking in python?
The compiling and linking allow the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.
The steps that are required in this as:
- Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp.
- Place this file in the Modules/ directory of the distribution which is getting used.
- Add a line in the file Setup.local that is present in the Modules/ directory.
- Run the file using spam file.o
- After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
- If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.
11) What is Polymorphism in Python?
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
12) Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
13) How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
14) What is the difference between deep and shallow copy?
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
15) What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
16) How can you randomize the items of a list in place in Python?
from random import shuffle
x = ['Code and Debug','Anirudh','Muskan','Vandana','Nihar','AKul']
shuffle(x)
print(x)
17) What is __init__?
__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = salary
E1 = Employee('Elon',44,1023400)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
18) How is memory managed in Python?
Memory is managed in Python in the following ways:
- Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
- The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
- Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
19) Explain the output of the following piece of code.
x = ["abcd", "pqrs"]
print(len(map(list, x)))
This actually gives us an error – a TypeError. This is because map() has no len() attribute in their dir().
20) What is a negative index in Python?
Python has a special feature like a negative index in Arrays and Lists. Positive index reads the elements from the starting of an array or list but in the negative index, Python reads elements from the end of an array or list.
mylist = ["Anirudh", "Developer", "Testing", "Coder", 23, 11, "Hello"]
print(mylist[-1])
print(mylist[-3])