Python has become the most popular programming language and there are many Python interviews happening. I have been going through some of the interviews and found that many of the questions are repeatedly asked. So, I am summarizing some of the questions here with possible answers. Note that questions marked with * are more fequently asked ones.
Interview questions for entry level programmer:
Expand All Questions Collapse All QuestionsQuestion 1: What is Python?
Short Answer: Python is a free, open source, high-level, interpreted programming language known for its simplicity and readability. Key features like supporting multiple paradigms of programming like procedural and object-oriented programming, dynamic typing, extensive libraries, and cross-platform compatibility make it a general-purpose language.
Explanation: Python is one of the most widely used programming language because of being platform independent, interpreted, dynamically typed and high-level language. Which makes it one of the best programming languages to learn and use easily. It is also a free and open-source language. Python supports both procedural and object-oriented programming and is used to perform general-purpose programming which means it can be used for multiple purposes like server-side web development, mathematical and scientific calculations, data analytics and visualization, data science, image, data and video processing, machine learning and artificial intelligence, scripting for automation, game development, web scraping, desktop application development etc.
Question 1.1: Is Python interpreted or compiled?
Answer: The most popular and widely used implementation of Python specification, CPython is considered interpreted in nature, but if we go into python process of converting source code to machine language we have few internal steps involved like implicit compilation to bytecode and interpretation of bytecode by Python virtual machine. The developer don’t have to separately compile python code to bytecode. The intermediate temporary bytecode with extension “pyc” is stored in __pycahce__ directory which is recompiled every time the code runs. The python code can be manually compiled to pyc files using internal modules of python like “compileall”, which doesn’t give any advantage in execution of code. e.g:
python -m compileall python_source.py
However, as pyc files can’t be distributed to run on end user machine, there is no reason to explicitly compile python code. Only developed python code with python interpreter can run on end user machine, which significantly add to the argument of python being an interpreted language only.
“Nuitka” python compiler translates python source to C program and then convert it to machine executable code. So,Python being interpreted or compiled dependents on how the implementation of Python performs it.
NOTE: If we refer Python being a Python language specification the implementations of it can be anything compiled or interpreted based on how it is converting the python code to machine understandable code and how it is distributed. CPython, PyPy are interpreters and Nuitka is compiler.
Question 1.2: What is a compiled language?
Answer: Compilation is the process in which source code is translated to machine code in one go. On every change to source code the compilation process needs to be repeated. The final machine code known as executable can be distributed worldwide without need to distribute the compiler. A language using compilation process to generate machine code is a compiled language.
Question 1.3: What is an interpreted language?
Answer: The process in which every time source code is needed to be translated to machine code when a program needs to be run, and no executable file is generated, is called interpretation. Most interpreted languages use line by line interpretation. When a program written in interpreted language is distributed the interpreter for the language also need to be present in destination machine. A programming language using interpretation for execution are called interpreted languages.
* Question 2: What is __init__ method?
Answer: The __init__ method is a special method in Python classes, known as a constructor. It is automatically called when an instance of the class is created, allowing you to initialize the object’s attributes.
Related Questions:
Question 2.1: What happens if we do not define __init__ method in class?
Answer: If you do not define an __init__ method, Python will use a default constructor that does nothing. You can still create instances of the class, but you won’t be able to initialize attributes during instantiation.
Question 2.2: Can __init__ method return a value?
Answer: No, the __init__ method cannot return a value. It must return None implicitly. Attempting to return a value will result in TypeError.
Question 2.3: Can you overload the __init__ method in python?
Python does not support method overloading in the traditional sense. However, you can achieve similar functionality using default arguments or variable-length arguments (*args and **kwargs).
Question 2.4: How do you define __init__ method in class?
Answer: The __init__ method is defined with the def keyword, followed by __init__(self, … ), where self refers to the instance being created and additional parameters can be added to initialize the object’s attributes.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(person.name) # Output: Alice
print(person.age) # Output: 30
Question 2.5: How can you call the __init__ method of parent class in subclass?
Answer: You can call __init__ method of superclass into subclass using super().
Example:
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
Question 2.6: Is __init__ method a private method?
Answer: The __init__ method in Python is not private. It is a special method, also known as a constructor, used to initialize an object’s attributes.
Question 3: What is __new__ method in python?
Answer: The __new__ method in Python is a special method responsible for creating a new instance of a class. It is called before the __init__ method and is rarely overridden. The __new__ method is used to control the creation of a new instance, while the __init__ method is used to initialize the instance. It is called with the class itself as the first argument, followed by any additional arguments that were passed to the class constructor. The __new__ method is typically overridden when you need to control the creation of a new instance, such as when implementing singleton patterns or immutable objects. The __new__ method has following structure:
class MyClass:
def __new__(cls, *args, **kwargs):
# Create a new instance of the class
instance = super().__new__(cls)
return instance
def __init__(self, value):
self.value = value
Related Question:
Question 3.1: What is the use of __new__ method in python?
Answer: The __new__ method in Python is used in specific scenarios where you need to control the creation of a new instance of a class. Here are some situations where you might use __new__:
Singleton Pattern: If you want to implement a singleton pattern (where only one instance of a class is allowed), you can use __new__ to control the instantiation process and ensure only one instance is created.
Customizing Instance Creation: If you need to customize the instance creation process, such as pre-allocating resources or setting up certain conditions before the instance is created, __new__ can be used.
Immutable Objects: When creating immutable objects like tuples or strings, you might need to use __new__ to ensure the object is properly created before any attributes are set.
Metaclasses: When working with metaclasses, __new__ is often used to customize the creation of classes themselves.
Question 3.2: Write code to implement singleton using __new__ method. / Write a code to demonstrate use of __new__ method.
Here’s an example of using __new__ to implement a singleton pattern:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
def __init__(self, value):
self.value = value
obj1 = Singleton(10)
obj2 = Singleton(20)
print(obj1.value) # Output: 10
print(obj2.value) # Output: 10
print(obj1 is obj2) # Output: True
* Question 4: What is the difference between __init__ and __new__ methods of a class in python?
Answer: The __new__ method is responsible for creating a new instance of a class, while the __init__ method initializes the instance. __new___ is called before __init__ and is rarely overridden. Here’s an example to illustrate:
class MyClass:
def __new__(cls, *args, **kwargs):
instance = super().__new__(cls)
return instance
def __init__(self, value):
self.value = value
obj = MyClass(10)
print(obj.value) # Output: 10
Question 5: What are *args and **kwargs in python modules? / How do you provide variable number of arguments to a python module?
Answer: In Python, *args and **kwargs are used to pass a variable number of arguments to a function. They are useful when you want to create functions that can handle an arbitrary number of inputs.
*args:
*args allows you to pass a variable number of non-keyword arguments to a function.
It collects the arguments into a tuple.
Example:
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3) # Output: 1 2 3
**kwargs:
**kwargs allows you to pass a variable number of keyword arguments to a function.
It collects the arguments into a dictionary.
Example:
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key} = {value}")
my_function(name="Alice", age=30) # Output: name = Alice age = 30
*args and *kwargs:
You can use both *args and **kwargs in the same function to accept both positional and keyword arguments.
Example:
def my_function(*args, **kwargs):
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key} = {value}")
my_function(1, 2, 3, name="Alice", age=30)
# Output:
# 1
# 2
# 3
# name = Alice
# age = 30
These features make your functions more flexible and capable of handling a wide range of input scenarios.
Question 6: What exactly happens when we write an ‘import’ statement?
Answer: The python interpreter tries to look for the directory containing the module we are trying to import in sys.path. It is a list of directories that Python will search once it is done looking at the cached modules and Python standard library modules.
Question 7: What are modules and packages in python?
Answer:
Modules: A module is a single file (or files) that are imported under one import and used. It is simply a Python file with a .py extension that contains functions, classes, or variables.
Package: A package is a collection of modules in directories that give a package hierarchy. It is a way of organizing related modules into a single directory hierarchy. A package typically contains an __init__.py file to indicate that the directory is a package. This file can also execute initialization code for the package. After python 3.3 and PEP 420, creating __init__.py file is optional and python will automatically detect namespaces with folders having python module files.
Related Questions:
Question 7.1: Provide an example of packages and modules.
Answer:
Suppose you have the following directory structure:
example_package/
__init__.py
example_module.py
and math_utils.py module has following code:
def example_function():
print("This is an example of function under module in a package")
The python module can be imported into another code like below:
from example_package import example_module
example_module.example_function() # prints "This is an example ..... "
Question 8: What’s the need for PYTHONPATH?
Answer: PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages.
Question 9: What is the difference between List and Array in python?
Answer: Python list are heterogenous, which mean they can store different types of data in same list, while array are homogenous. List is built-in data type while arrays are part of standard library array. List is more flexible and easy to use in python and also have more built-in functions to utilize than array. Arrays can be fast and more efficient in the scenarios where large amount of homogenous data need to be processed. Python lists can store arrays as element in itself but arrays can’t store list as element because the arrays are homogenous and can only store some specific type of values like Unicode characters(‘u’,’w’), int(‘b’,’B’,’h’,’H’,’i’,’I’,’l’,’L’,’q’,’Q’) and float(‘f’,’d’) python data types, which need to be specified while creating arrays.
Realted Questions:
Question 9.1: Given an example of implementing List and Arrays in Python.
Answer: Following is one of the example of using list and array in python:
import array
my_array = array.array('i', [1, 2, 3, 4])
my_array.append(5)
print(my_array) # Output: array('i', [1, 2, 3, 4, 5])
my_list = [1,'two',3,4.0,5]
my_list.append(6)
print(my_list) # Output: [1, 'two', 3, 4.0, 5, 6]
Question 10: What is slicing in python?
Answer: Slicing in Python is a technique used to access a range of elements from sequences like arrays, lists, tuples, and strings. It allows you to extract a portion of a sequence by specifying a start, stop, and step value. The elements are returned from start index inclusive to stop index exclusive with step indexes to jump or skip.
Question 10.1: Give and example of slicing in python.
Answer: Following is an example of list, string and tuple slicing:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[2:7]) # Output: [2, 3, 4, 5, 6]
my_string = "Hello, World!"
print(my_string[:5]) # Output: Hello
print(my_string[::-1]) # Output: !dlroW ,olleH (reversed string)
my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(my_tuple[::3]) # Output: (0, 3, 6, 9)