Python Interview Questions and Answers (2021) - InterviewBit
Python Interview Questions and Answers (2021) - InterviewBit
Interviews?
Take FreePython
Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
Interview Questions and Answers (2020) | Python I…I…
This page will guide you on how to crack any python programming interview, including:
1. What is Python?
Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose
language, it can be used to build almost any type of application with the right tools/libraries. Additionally,
python supports objects, modules, threads, exception-handling and automatic memory management
which help in modelling real-world problems and building applications to solve these problems.
Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge
community of developers for Rapid Application Development and deployment.
Python being an interpreted language, executes each statement line by line and thus type-checking is
done on the fly, during execution. Hence, Python is a Dynamically Typed language.
Additionally, Python has an in-built garbage collection to recycle the unused memory for the private
heap space.
Local Namespace includes local names inside a function. the namespace is temporarily created for
a function call and gets cleared when the function returns.
Global Namespace includes names from various imported packages/ modules that is being used in
the current project. This namespace is created when the package is imported in the script and lasts
until the execution of the script.
Built-in Namespace includes built-in functions of core Python and built-in names for various types
of exceptions.
Lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an
object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner
namespace objects from an outer namespace.
Preparing for Python
Interviews?
Take Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
1. A local scope refers to the local objects available in the current function.
2. A global scope refers to the objects available throught the code execution since their inception.
3. A module-level scope refers to the global objects of the current module accessible in the program.
4. 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.
Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them -
log10() , acos() , exp() etc. To resolve this amiguity, it is necessary to prefix them with their
respective module, like math.exp() and cmath.exp() .
Consider the code below, an object temp has been initialized to 10 globally and then to 20 on
function call. However, the function call didn't change the value of the temp globally. Here, we can
observe that Python draws a clear line between global and local variables treating both their
namespaces as separate identities.
temp = 10 # global-scope variable
print(temp)
This behaviour can be overriden using the global keyword inside the function, as shown in the
following example:
def func():
global temp
print(temp)
defTake Free():
string_lowercase = func.lower()
return string_lowercase
return wrapper
def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper
def hello():
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.
def names_decorator(function):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
return string_hello
return wrapper
@names_decorator
11. 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
Preparing for Python
Interviews?
objects stored in both sequences can have different data types. Lists are represented with square
Take
brackets Free Mock
['sara', Test
(https://www.interviewbit.com/test/a/python-mock-test/)
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:
b = [7, 8, 9]
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]
A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or
work upon its inner elements.
my_list = [[10,20,30],[40,50,60],[70,80,90]]
# 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.
following catetgories-
None Type
None keyword represents the null values in Python. Boolean equality operation can be performed
Numeric Types
There are three distint numeric types - integers, floating-point numbers, and complex numbers.
Additionally, booleans are a sub-type of integers.
int Stores integer literals including hex, octal and binary numbers as integers
Stores literals containing decimal values and/or exponent sign as floating-point
float Preparing for Python
Interviews?
numbers
Take Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
Stores complex number in the form (A + Bj) and has attributes: real and
complex
imag
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:
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 after creation.
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.
mul = lambda a, b : a * b
def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
Take
pass
Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
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 are references 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.
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
So how does that make a difference? It sure does, because unlike range(), xrange() doesn't
generate a static list, it creates the value on the go. This technique is commonly used with an object
type generators and has been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can
lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough
memory for the generator (significantly less in comparison).
Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same 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.
1. Simplicity: Working on a single module helps you focus on a relatively small portion of the problem
at hand. This makes development easier and less error-prone.
2. Maintainability: Modules are designed to enforce logical boundaries between different problem
domains. If they are written in a manner that reduces interdependency, it is less likely that modifications
in a module might impact other parts of the program.
3. Reusability: Functions defined in a module can be easily reused by other parts of the application.
4. Scoping: Modules typically define a separate namespace, which helps avoid confusion between
identifiers from other parts of the program.
Modules, in general, are simply Python files with a .py extension and can have a set of functions,
classes or variables defined and implemented. They can be imported and initialized once using the
import statement. If partial functionality is needed, import the requisite classes or functions using from
Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the
modules into a folder and there you have it, the folder name as the package name. Importing a module
or its contents from this package requires the package name as prefix to the module name joined by a
dot.
Note: You can technically import the package as well, but alas, it doesn't import the modules within the
package to the local namespace, thus, it is practically useless.
object/instance is created. All classes have a __init__ method associated with them. It helps in
distinguishing methods and attributes of a class from local variables.
# class definition
class Student:
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
Continue skips the rest of the code in the current iteration and the control flows to the next
iteration of the loop.
Pass
and is similar to an empty statement represented by a semi-colon in languages
such as Java, C++, Javascript etc.
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
Pickling
Pickling is the name of the serialization process in Python.
Any object in Python can be serialized into a
byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects
can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the
serialization is portable across versions.
Unpickling
Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects
stored in the file, and loads the object to memory.
def fib(n):
p, q = 0, 1
yield p
p, q = q, p + q
x.__next__() # error
for i in fib(10):
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It
behaves differently with different objects, as it aims to produce the most relevant data, rather than the
complete information.
For Modules/Library objects, it returns a list of all attributes, contained in that module.
For Class Objects, it returns a list of all valid attributes and base attributes.
With no arguments passed, it returns a list of attributes in the current scope.
In Python, arguments are passed by reference, i.e., reference to the actual object is passed.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]
def __iter__(self):
self.pos = 0
return self
def __next__(self):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#...
#StopIteration
print("File Removed!")
import array
for i in a:
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
Take Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
for num in argv:
mul *= num
return mul
**kwargs
**kwargs is a special syntax used in function definition to pass variable-length keyworded argument.
Here, also, “kwargs” is used just by convention. You can use any other name.
Keyworded argument means a variable which has a name when passed to a function.
It is actually a dictionary of variable name and its value.
def tellArguments(**kwargs):
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3
39. 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 last element of array Arr[]
arr = [1, 2, 3, 4, 5, 6]
print(arr[-1]) #output 6
print(arr[-2]) #output 5
list1 = [3,4,5,2,0]
list1 = [3,5,2,1,0]
list1 = [3,4,5,2]
"Hello World"
"World Hello"
"dlroW olleH"
"olleH dlroW"
List is a sequence data type, while tuple is not.
Tuples are mutable but lists are immutable.
Tuple is a sequence data type, while lists is not.
Lists are mutable but tuples are immutable.
100000000000000000000
1e+20
100000000000000000000.0
1.0e+20
__init__ is called manually on object creation.
__init__ is a constructor method in Python.
All classes have a __init__ method associated with them.
__init__ allocates memory for objects.
Preparing for Python
Interviews?
Q - Which of the following is the function responsible for pickling?
Take Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
pickle.save()
pickle.store()
pickle.pickle()
pickle.dump()
__sara__
__ansh
_sara_
ansh__
Python namespaces are implemented as a dictionary in Python.
Python namespaces have keys as addresses of the objects.
Lifecycle of a namespace depends upon the scope of the objects they are mapped to.
Namespaces ensure that object names in a program are unique.
Q - Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'] , what
is the output of ["".join([i, j]) for i, j in zip(list1, list2)] ?
['s', 'a', 'r', 'a', 'a', 'n', 's', 'h']
['s', 'r', 'a', 's', 'a', 'a', 'n', 'h']
['sa', 'ra', 'an', 'sh']
['sa', 'sa', 'sn', 'sh', 'ra', 'ra', 'rn', 'rh', 'aa', 'aa', 'an', 'ah', 'sa', 'sa', 'sn', 'sh']
Current time.
Current time in milliseconds.
Current time in milliseconds since midnight, January 1, 1970.
Current time in milliseconds since midnight, January 1, 1970 GMT (the Unix time).
Preparing for Python
Interviews?
Take Free Mock Test
(https://www.interviewbit.com/test/a/python-mock-test/)
Blog (https://www.interviewbit.com/blog/)
About Us (/pages/about_us/)
FAQ (/pages/faq/)
Contact Us (/pages/contact_us/)
Terms (/pages/terms/)
Privacy Policy (/pages/privacy/)
Like Us
(https://www.facebook.com/interviewbit)
Follow Us
(https://twitter.com/interview_bit)
Email
(mailto:hello@interviewbit.com)