Python Interview Questions
Python Interview Questions
Easy
Asked in
Easy
Asked in
Asked in
Represents the NULL values in
NoneType
Python.
Numeric Types:
There are three distinct numeric types - integers, floating-point
numbers, and complex numbers. Additionally, booleans are a sub-
type of integers.
Class
Description
Name
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.
Class Name Description
Stores comma-separated list of key:
dict
value pairs
Set Types:
Currently, Python has two built-in set types
- set and frozenset. set type is mutable and supports methods
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.
The function used for the above process is pickle.load().
**kwargs
**kwargs is a special syntax used in the function definition to
pass variable-length keyworded arguments.
Here, also, “kwargs” is used just by convention. You can use any
other name.
Keyworded argument means a variable that has a name when passed to
a function.
It is actually a dictionary of the variable names and its value.
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
To access the name attribute, we just call the attribute using the
dot operator as shown below:
print(emp_1.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)
def introduce(self):
print("Hello I am " + self.emp_name)
# 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()
# 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()
# 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
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()
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)
# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)
class Child(Parent):
pass
# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False
df = pd.DataFrame(data_info)
#To add new column third
df['third']=pd.Series([10,20,30],index=['a','b','c'])
print (df)
#To add new column fourth
df['fourth']=df['first']+info['third']
print (df)
56. How will you delete indices, rows and columns from a
dataframe?
To delete an Index:
Execute del df.index.name for removing the index by name.
The axis argument is passed to the drop method where if the value
is 0, it indicates to drop/delete a row and if 1 it has to drop
the column.
Additionally, we can try to delete the rows/columns in place by
setting the value of inplace to True. This makes sure that the job
is done without the need for reassignment.
The duplicate values from the row/column can be deleted by using
the drop_duplicates() method.
57. Can you get items of series A that are not available
in another series B?
This can be achieved by using the ~ (not/negation symbol)
import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1=df1[~df1.isin(df2)]
print(df1)
"""
Output:
0 2
1 4
dtype: int64
"""
58. How will you get the items that are not common to
both the given series A and B?
We can achieve this by first performing the union of both series,
then taking the intersection of both series. Then we follow the
approach of getting items of union that are not there in the list
of the intersection.
The following code demonstrates this:
import pandas as pd
import numpy as np
df1 = pd.Series([2, 4, 5, 8, 10])
df2 = pd.Series([8, 10, 13, 15, 17])
p_union = pd.Series(np.union1d(df1, df2)) # union of series
p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series
unique_elements = p_union[~p_union.isin(p_intersect)]
print(unique_elements)
"""
Output:
0 2
1 4
2 5
5 13
6 15
7 17
dtype: int64
"""
2D array creation:
import numpy as np
two_dimensional_list=[[1,2,3],[4,5,6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is : ",two_dimensional_arr)
3D array creation:
import numpy as np
three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]]
three_dimensional_arr = np.array(three_dimensional_list)
print("3D array is : ",three_dimensional_arr)
ND array creation: This can be achieved by giving the ndmin
attribute. The below example demonstrates the creation of a 6D
array:
import numpy as np
ndArray = np.array([1, 2, 3, 4], ndmin=6)
print(ndArray)
print('Dimensions of array:', ndArray.ndim)
Solution:
import numpy as np
#inputs
inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])
new_col = np.array([[20,30,40]])
# delete 2nd column
arr = np.delete(inputArray , 1, axis = 1)
#insert new_col to array
arr = np.insert(arr , 1, new_col, axis = 1)
print (arr)
64. How will you efficiently load data from a text file?
We can use the method numpy.loadtxt() which can automatically read
the file’s header and footer lines and the comments if any.
This method is highly efficient and even if this method feels less
efficient, then the data should be represented in a more efficient
format such as CSV etc. Various alternatives can be considered
depending on the version of NumPy used.
Following are the file formats that are supported:
Text files: These files are generally very slow, huge but portable
and are human-readable.
Raw binary: This file does not have any metadata and is not
portable. But they are fast.
Pickle: These are borderline slow and portable but depends on the
NumPy versions.
HDF5: This is known as the High-Powered Kitchen Sink format which
supports both PyTables and h5py format.
.npy: This is NumPy's native binary data format which is extremely
simple, efficient and portable.
65. How will you read CSV data into an array in NumPy?
This can be achieved by using the genfromtxt() method by setting
the delimiter as a comma.
from numpy import genfromtxt
csv_data = genfromtxt('sample_file.csv', delimiter=',')
66. How will you sort the array based on the Nth column?
For example, consider an array arr.
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
Let us try to sort the rows by the 2nd column so that we get:
[[6, 1, 4],
[8, 3, 2],
[3, 6, 5]]
We can do this by using the sort() method in numpy as:
import numpy as np
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
#sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
order=['f1'],
axis=0).view(np.int)
We can also perform sorting and that too inplace sorting by doing:
arr.view('i8,i8,i8').sort(order=['f1'], axis=0)
67. How will you find the nearest value in a given numpy
array?
We can use the argmin() method of numpy as shown below:
import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645
68. How will you reverse the numpy array using one line
of code?
This can be done as shown in the following:
reversed_array = arr[::-1]
of .py. This file will have classes and functions that are
reusable in the code as well as across modules.
A python package is created by following the below steps:
Create a directory and give a valid name that represents its
operation.
Place modules of one kind in this directory.
Create __init__.py file in this directory. This lets python know
the directory we created is a package. The contents of this
package can be imported across different modules in other packages
to reuse the functionality.
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
72. What are lambda functions?
Lambda functions are generally inline, anonymous functions
represented by a single expression. They are used for creating
function objects during runtime. They can accept any number of
parameters. They are usually used where functions are required
only for a short period. They can be used as:
mul_func = lambda x,y : x*y
print(mul_func(6, 4))
# Output: 24
# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 3
print_pairs(arr, N)
Conclusion:
In this article, we have seen commonly asked interview questions
for a python developer. These questions along with regular problem
practice sessions will help you crack any python based interviews.
Over the years, python has gained a lot of popularity amongst the
developer’s community due to its simplicity and ability to support
powerful computations. Due to this, the demand for good python
developers is ever-growing. Nevertheless, to mention, the perks of
being a python developer are really good. Along with theoretical
knowledge in python, there is an emphasis on the ability to write
good quality code as well. So, keep learning and keep practicing
problems and without a doubt, you can crack any interviews.
Important Resources:
Python Basic Programs
Python MCQ
Python Commands
Python Developer Resume
Python Projects
Difference Between Python 2 and 3
Python Frameworks
Python Documentation
Numpy Tutorial
Python Vs R
Python Vs Javascript
Difference Between C and Python
Python Vs Java
Features of Python
Golang vs Python
Python Developer Skills
Python MCQ
1.
3.
of func(float(10),20) ?
5.
Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'],
list2)]?
10.
11.
class B(A):
def __init__(self, a):
X.__init__(self, a)
def mul_three(self):
self.num *= 3
obj = B(4)
print(obj.num)
obj.mul_two()
print(obj.num)
obj.mul_three()
print(obj.num)
12.
def getHumanName(self):
return self.human_name
def isEmployee(self):
return False
class IBEmployee(Human):
def __init__(self, name, emp_id):
super(IBEmployee, self).__init__(name)
self.emp_id = emp_id
def isEmployee(self):
return True
def get_emp_id(self):
return self.emp_id
# Driver code
employee = IBEmployee("Mr Employee", "IB007")
print(employee.getHumanName(), employee.isEmployee(), employee.get_emp_id()
13.
Which among the below options will correct the below error
obtained while reading “sample_file.csv” in pandas?
Traceback (most recent call last): File "<input>", line 10, in<module>
UnicodeEncodeError:
'ascii' codec can't encode character.
14.
How will you find the location of numbers which are multiples of 5
in a series?
import pandas as pd
import numpy as np
series_data = pd.Series(np.random.randint(1, 20, 7))
#insert code here
16.
first_name = "XYZ"
person = Person(first_name, "ABC")
first_name = "LMN"
person.last_name = "PQR"
print(person.first_name, person.last_name)
17.
Which among the below options picks out negative numbers from the
given list.
18.
19.
What is the output of the below code?
class X:
def __init__(self):
self.__num1 = 5
self.num2 = 2
def display_values(self):
print(self.__num1, self.num2)
class Y(X):
def __init__(self):
super().__init__()
self.__num1 = 1
self.num2 = 6
obj = Y()
obj.display_values()