Python Interview Qn A
Python Interview Qn A
© Copyright by Interviewbit
If you're a Python Developer looking to learn more, the guidance of an
expert might complement the insights from the book. If you're
interested, feel free to register for our FREE upcoming Masterclass,
where you can interact with a top instructor, LIVE
Introduction to Python:
Python was developed by Guido van Rossum and was released first on February 20,
1991. It is one of the most widely-used and loved programming languages and is
interpreted in nature thereby providing flexibility of incorporating dynamic
semantics. It is also a free and open-source language with very simple and clean
syntax. This makes it easy for developers to learn python. Python also supports
object-oriented programming and is most commonly used to perform general-
purpose programming.
Due to its simplistic nature and the ability to achieve multiple functionalities in fewer
lines of code, python’s popularity is growing tremendously. Python is also used in
Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and
various other domains due to its ability to support powerful computations using
powerful libraries. Due to this, there is a huge demand for python developers in India
and across the world. Companies are willing to offer amazing perks and benefits to
these developers.
In this article, we will see the most commonly asked python interview questions and
answers which will help you excel and bag amazing job offers.
We have classified them into the following sections:
A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution
since their inception.
A module-level scope refers to the global objects of the current module
accessible in the program.
An outermost scope refers to all the built-in names callable in the program. The
objects in this scope are searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords
such as global.
6. What are lists and tuples? What is the key difference between
the two?
Lists and Tuples are both sequence data types that can store a collection of objects
in Python. The objects stored in both sequences can have different data types. Lists
are represented with square brackets ['sara', 6, 0.19] , while tuples are
represented with parantheses ('ansh', 5, 0.97) .
But what is the real difference between the two? The key difference between the two
is that while lists are mutable, tuples on the other hand are immutable objects.
This means that lists can be modified, appended or sliced on the go but tuples
remain constant and cannot be modified in any manner. You can run the following
example on Python IDLE to confirm the difference:
There are several built-in data types in Python. Although, Python doesn't require data
types to be defined explicitly during variable declarations type errors are likely to
occur if the knowledge of data types and their compatibility with each other are
neglected. Python provides type() and isinstance() functions to check the type
of these variables. These data types can be grouped into the following categories-
None Type:
None keyword represents the null values in Python. Boolean equality
operation can be performed using these NoneType objects.
Numeric Types:
There are three distinct numeric types - integers, floating-point numbers, and
complex numbers. Additionally, booleans are a sub-type of integers.
Note: The standard library also includes fractions to store rational numbers and
decimal to store floating-point numbers with user-defined precision.
Sequence Types:
According to Python Docs, there are three basic Sequence Types - lists, tuples,
and range objects. Sequence types have the in and not in operators
defined for their traversing their elements. These operators share the same
priority as the comparison operations.
Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str .
Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings
objects are mutable and there is currently only one standard mapping type, the
dictionary.
Set Types:
Currently, Python has two built-in set types - set and frozenset. set type is
mutable and supports methods like add() and remove() . frozenset type is
immutable and can't be modified a er creation.
Note: set is mutable and thus cannot be used as key for a dictionary. On the other
hand, frozenset is immutable and thus, hashable, and can be used as a dictionary
key or as an element of another set.
Modules:
Module is an additional built-in type supported by the Python Interpreter. It
supports one special operation, i.e., attribute access: mymod.myobj , where
mymod is a module and myobj references a name defined in m's symbol table.
The module's symbol table resides in a very special attribute of the module
__dict__, but direct assignment to this module is neither possible nor
recommended.
Callable Types:
Callable types are the types to which function call can be applied. They can be
user-defined functions, instance methods, generator functions, and some
other built-in functions, methods and classes.
Refer to the documentation at docs.python.org for a detailed view of the
callable types.
def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block
Global variables are public variables that are defined in the global scope. To use
the variable in the global scope inside a function, we use the global keyword.
Protected attributes are attributes defined with an underscore prefixed to their
identifier eg. _sara. They can still be accessed and modified from outside the
class they are defined in but a responsible developer should refrain from doing
so.
Private attributes are attributes with double underscore prefixed to their
identifier eg. __ansh. They cannot be accessed or modified from the outside
directly and will result in an AttributeError if such an attempt is made.
# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
print(current) # output => 0
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.
import array
a = array.array('i', [1, 2, 3])
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (g
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string
This behavior can be overridden using the global keyword inside the function, as
shown in the following example:
The beauty of the decorators lies in the fact that besides adding functionality to the
output of the method, they can even accept arguments for functions and can further
modify those arguments before passing it to the function itself. The inner nested
function, i.e. 'wrapper' function, plays a significant role here. It is implemented to
enforce encapsulation and thus, keep itself hidden from the global scope.
Python comprehensions, like decorators, are syntactic sugar constructs that help
build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or
set. Using comprehensions saves a lot of time and code that might be considerably
more verbose (containing more lines of code). Let's check out some examples, where
comprehensions can be truly beneficial:
Performing mathematical operations on the entire list
a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)] # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b] # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]
Note: List comprehensions have the same effect as the map method in other
languages. They follow the mathematical set builder notation rather than map
and filter functions in Python.
mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10
def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10
Shallow Copy is a bit-wise copy of an object. The copied object created has an exact
copy of the values in the original object. If either of the values is a reference to other
objects, just the reference addresses for the same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even
duplicates the objects referenced by the source object.
Note: xrange has been deprecated as of Python 3.x. Now range does exactly the
same as what xrange used to do in Python 2.x, since it was way better to use
xrange() than the original range() function in Python 2.x.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]
class ArrayList:
def __init__(self, number_list):
self.numbers = number_list
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration
import os
os.remove("ChangedFile.csv")
print("File Removed!")
**kwargs
def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3
38. What are negative indexes and why are they used?
Negative indexes are the indexes from the end of the list or tuple or string.
Arr[-1] means the last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
To instantiate or create an object from the class created above, we do the following:
emp_1=InterviewbitEmployee("Mr. Employee")
To access the name attribute, we just call the attribute using the dot operator as
shown below:
print(emp_1.emp_name)
# Prints Mr. Employee
To create methods inside the class, we include the methods under the scope of the
class as shown below:
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
def introduce(self):
print("Hello I am " + self.emp_name)
The self parameter in the init and introduce functions represent the reference to the
current class instance which is used for accessing attributes and methods of that
class. The self parameter has to be the first parameter of any method defined inside
the class. The method of the class InterviewbitEmployee can be accessed as shown
below:
emp_1.introduce()
class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name
def introduce(self):
print("Hello I am " + self.emp_name)
# Parent class
class ParentClass:
def par_func(self):
print("I am parent class function")
# Child class
class ChildClass(ParentClass):
def child_func(self):
print("I am child class function")
# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()
# Parent class
class A:
def __init__(self, a_name):
self.a_name = a_name
# Intermediate class
class B(A):
def __init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)
# Child class
class C(B):
def __init__(self,c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)
def display_names(self):
print("A name : ", self.a_name)
print("B name : ", self.b_name)
print("C name : ", self.c_name)
# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()
Multiple Inheritance: This is achieved when one child class derives members
from more than one parent class. All features of parent classes are inherited in
the child class.
# Parent class1
class Parent1:
def parent1_func(self):
print("Hi I am first Parent")
# Parent class2
class Parent2:
def parent2_func(self):
print("Hi I am second Parent")
# Child class
class Child(Parent1, Parent2):
def child_func(self):
self.parent1_func()
self.parent2_func()
# Driver's code
obj1 = Child()
obj1.child_func()
Hierarchical Inheritance: When a parent class is derived by more than one child
class, it is called hierarchical inheritance.
# Base class
class A:
def a_func(self):
print("I am from the parent class.")
# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func() #child 1 method
obj2.a_func()
obj2.c_func() #child 2 method
Following are the ways using which you can access parent class members within a
child class:
By using Parent class name: You can use the name of the parent class to access
the attributes as shown in the example below:
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age
def display(self):
print(Parent.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
By using super(): The parent class members can be accessed in child class using
the super keyword.
class Parent(object):
# Constructor
def __init__(self, name):
self.name = name
class Child(Parent):
# Constructor
def __init__(self, name, age):
'''
In Python 3.x, we can also use super().__init__(name)
'''
super(Child, self).__init__(name)
self.age = age
def display(self):
# Note that Parent.name cant be used
# here since super() is used in the constructor
print(self.name, self.age)
# Driver Code
obj = Child("Interviewbit", 6)
obj.display()
# protected members
_emp_name = None
_age = None
# private members
__branch = None
# constructor
def __init__(self, emp_name, age, branch):
self._emp_name = emp_name
self._age = age
self.__branch = branch
#public member
def display():
print(self._emp_name +" "+self._age+" "+self.__branch)
class EmptyClassDemo:
pass
obj=EmptyClassDemo()
obj.name="Interviewbit"
print("Name created= ",obj.name)
Output:
Name created = Interviewbit
class InterviewbitEmployee:
# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)
class Parent(object):
pass
class Child(Parent):
pass
# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False
obj1 = Child()
obj2 = Parent()
print(isinstance(obj2, Child)) #False
print(isinstance(obj2, Parent)) #True
import pandas as pd
dataframe = pd.DataFrame( data, index, columns, dtype)
where:
We can use the shape attribute of the numpy array to find the shape. It returns the
shape of the array in terms of row count and column count of the array.
import numpy as np
arr_two_dim = np.array([("x1","x2", "x3","x4"),
("x5","x6", "x7","x8" )])
arr_one_dim = np.array([3,2,4,5,6])
# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)
"""
Output:
2-D Array Shape: (2, 4)
1-D Array Shape: (5,)
"""
71. What are some of the most commonly used built-in modules
in Python?
Python modules are the files having python code which can be functions, variables or
classes. These go by .py extension. The most commonly available built-in modules
are:
os
math
sys
random
re
datetime
JSON
import random
print(random.random())
import random
print(random.randrange(5,100,2))
74. Can you easily check if all characters in the given string is
alphanumeric?
This can be easily done by making use of the isalnum() method that returns true in
case the string has only alphanumeric characters.
For Example -
Another way is to use match() method from the re (regex) module as shown:
import re
print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False
Based on the above diagram, there are three threads. First Thread acquires the GIL
first and starts the I/O execution. When the I/O operations are done, thread 1 releases
the acquired GIL which is then taken up by the second thread. The process repeats
and the GIL are used by different threads alternatively until the threads have
completed their execution. The threads not having the GIL lock goes into the waiting
state and resumes execution only when it acquires the lock.
79. Are there any tools for identifying bugs and performing
static analysis in python?
Yes, there are tools like PyChecker and Pylint which are used as static analysis and
linting tools respectively. PyChecker helps find bugs in python source code files and
raises alerts for code issues and their complexity. Pylint checks for the module’s
coding standards and supports different plugins to enable custom features to meet
this requirement.
Shallow copy does the task of creating new objects storing references of original
elements. This does not undergo recursion to create copies of nested objects. It
just copies the reference details of nested objects.
Deep copy creates an independent and new copy of an object and even copies
all the nested objects of the original element recursively.
def main():
print("Hi Interviewbit!")
if __name__=="__main__":
main()
def function_name(*arg_list)
For example: