You are on page 1of 15

Interview Guide

PYTHON

Interview Guide
1 | www.simplilearn.com
Ace Your Python
Interview
Today, the world of Big Data and Are you applying for a job that
Analytics has gained enormous involves knowledge of Python? If yes,
popularity and consequently, we have your back. We have clubbed a
Python has become the preferred list of 50 most popular questions you
programming language among tech can expect in an interview. So prepare
professionals. Scalability, simpler ahead of time, and crack your python-
coding, and its collection of libraries related interview in the first go.
and frameworks are just some of the
features that make Python suitable
for companies engaged in data or
machine learning-based initiatives.

2 | www.simplilearn.com
Interview Guide

Topics
Covered

• Python Operators

• Lists, Tuples and Dictionaries

• Python Arrays

• Output questions

• Django

• Python in-built functions

• Numpy and Pandas

• Matplotlib

• Scikit Learn

3 | www.simplilearn.com
Interview Guide

Q: What Is the Difference Between a Shallow Copy and Deep Copy?

A: Deepcopy creates a different object and populates it with the child objects of
the original object. Therefore, changes in the original object are not reflected in
the copy.

copy.deepcopy() creates a Deep Copy.

Shallow copy creates a different object and populates it with the references of
the child objects within the original object. Therefore, changes in the original
object are reflected in the copy.

copy.copy creates a Shallow Copy.

Q: How Is Multithreading Achieved in Python?

A: Multithreading usually implies that multiple threads are executed concurrently.


The Python Global Interpreter Lock doesn't allow more than one thread to
hold the Python interpreter at that particular point of time. So multithreading
in python is achieved through context switching. It is quite different from
multiprocessing which actually opens up multiple processes across multiple
threads.

Q: Discuss Django Architecture.

A: Django is a web service used to build your web pages. Its architecture is as
shown:
Template: the front end of the web page
Model: the back end where the data is stored
View: It interacts with the model and template and maps it to the URL
Django: serves the page to the user

Q: What Advantage Does the Numpy Array Have over a Nested List?

A: Numpy is written in C so that all its complexities are backed into a simple to use
a module. Lists, on the other hand, are dynamically typed. Therefore, Python
must check the data type of each element every time it uses it. This makes
Numpy arrays much faster than lists.

Numpy has a lot of additional functionality that list doesn’t offer; for instance, a
lot of things can be automated in Numpy.

Q: What are Pickling and Unpickling?

4 | www.simplilearn.com
Interview Guide

Pickling Unpickling
Converting a Python object Converting a byte stream to
hierarchy to a byte stream is a Python object hierarchy is
called pickling called unpickling

Pickling is also referred to as Unpickling is also referred to as


serialization deserialization

If you just created a neural network model, you can save that model to your
hard drive, pickle it, and then unpickle to bring it back into another software
program or to use it at a later time.

Q: How is Memory managed in Python?


A: Python has a private heap space that stores all the objects. The Python
memory manager regulates various aspects of this heap, such as sharing,
caching, segmentation, and allocation. The user has no control over the heap;
only the Python interpreter has access.

Q: Are Arguments in Python Passed by Value or by Reference?

A: Arguments are passed in python by a reference. This means that any changes
made within a function are reflected in the original object.
Consider two sets of code shown below:

In the first example, we only assigned a value to one element of ‘l’, so the
output is [3, 2, 3, 4].
In the second example, we have created a whole new object for ‘l’. But, the
values [3, 2, 3, 4] doesn’t show up in the output as it is outside the definition of
the function.

5 | www.simplilearn.com
Interview Guide

Q: How Would You Generate example - The program below


Random Numbers in Python? prints a string ignoring the spaces.
var="Si mplilea rn"
A: To generate random numbers in
Python, you must first import the for i in var:
random module.
if i==" ":
The random() function generates a pass
random float value between 0 & 1.
else:
> random.random() print(i,end="")
Here, the pass statement refers to
The randrange() function
‘no action required.’
generates a random number within
a given range.

Syntax: randrange(beginning, end, Q: How Will You Check If All the


step) Characters in a String Are
Alphanumeric?
Example - > random.
randrange(1,10,2) A: Python has an inbuilt method
isalnum() which returns true if
Q: What Does the // Operator Do? all characters in the string are
alphanumeric.
A: In Python, the / operator performs
Example -
division and returns the quotient in
the float. >> "abcd123".isalnum()
For example: 5 / 2 returns 2.5 Output: True
The // operator, on the other hand, >>”abcd@123#”.isalnum()
returns the quotient in integer. Output: False
For example: 5 // 2 returns 2 Another way is to use regex as
shown.
Q: What Does the ‘is’ Operator Do? >>import re
A: The ‘is’ operator compares the id >>bool(re.match(‘[A-Za-z0-
of the two objects. 9]+$','abcd123’))
Output: True
list1=[1,2,3]
>> bool(re.match(‘[A-Za-z0-
list2=[1,2,3]
9]+$','abcd@123’))
list3=list1
Output: False
list1 == list2 True
list1 is list2 False
Q: How Will You Merge Elements
list1 is list3 True in a Sequence?

A: There are three types of sequences


Q: What Is the Purpose of the Pass
in Python:
Statement?
Lists
A: The pass statement is used when
there's a syntactic but not an
Tuples
operational requirement. For Strings

6 | www.simplilearn.com
Interview Guide

Example of Lists - John?


>>l1=[1,2,3]
>>l2=[4,5,6] Q: What Is the Difference Between
>>l1+l2 Del and Remove() on Lists?
Output: [1,2,3,4,5,6] A: Del
Example of Tuples - Del removes all elements of a list
>>t1=(1,2,3) within a given range
>>t2=(4,5,6) Syntax: del list[start:end]
>>t1+t2
Output: (1,2,3,4,5,6) Remove()
Example of String - removes the first occurrence of a
>>s1=“Simpli” particular character

>>s2=“learn” Syntax: list.remove(element)


>>s1+s2
Output: ‘Simplilearn’ Here is an example to understand
the two statements -
>>lis=[‘a’, ‘b’, ‘c’, ‘d’]
Q: How Would You Remove
>>del lis[1:3]
All Leading Whitespace in a
String? >>lis
Output: [“a”,”d”]
A: Python provides the inbuilt
function lstrip() to remove all >>lis=[‘a’, ‘b’, ‘b’, ‘d’]
leading spaces from a string. >>lis.remove(‘b’)
>>“ Python”.lstrip >>lis
Output: Python Output: [‘a’, ‘b’, ‘d’]
Note that in the range 1:3, the
Q: How Would You Replace All elements are counted up to 2 and
Occurrences of a Substring not 3.
with a New String?

A: The replace() function can be Q: How Do You Display the


used with strings for replacing Contents of a Text File in
a substring with a given string. Reverse Order?
Syntax:
A: You can display the contents of a
str.replace(old, new, count) text file in reverse order using the
replace() returns a new string following steps:
without modifying the original Open the file using the open()
string. function
Example -
Store the contents of the file into a
>>"Hey John. How are you, John?". list
replace(“john",“John",1)
Reverse the contents of the list
Output: “Hey John. How are you,

7 | www.simplilearn.com
Interview Guide

Run a for loop to iterate through A: Output:


the list list1 = [1,’a’]
list2 = [123]
Q: Differentiate Between append() lilst3 = [1,’a’]
and extend().
Note that list1 and list3 are equal.
A: append() When we passed the information
to the addToList, we did it without
append() adds an element to the a second value. If we don't have
end of the list an empty list as the second value,
Example - it will start off with an empty list,
which we then append. For list2,
>>lst=[1,2,3] we appended the value to an
>>lst.append(4) empty list, so its value becomes
[123].
>>lst
For list3, we're adding ‘a’ to the list.
Output:[1,2,3,4]
Because we didn't designate the
list, it is a shared value. It means
the list doesn’t reset and we get its
extend()
value as [1, ‘a’].
extend() adds elements from an
Remember that a default list is
iterable to the end of the list
created only once during the
Example - function and not during its call
number.
>>lst=[1,2,3]
>>lst.extend([4,5,6])
>>lst Q: What Is the Difference Between
a List and a Tuple?
Output:[1,2,3,4,5,6]
A: Lists are mutable while tuples are
immutable.
Q: What Is the Output of the
Example:
below Code? Justify Your
Answer. List
>>lst = [1,2,3]
>>def addToList(val, list=[]):
>>lst[2] = 4
>> list.append(val) >>lst
>> return list Output:[1,2,4]
Tuple
>>list1 = addToList(1)
>>tpl = (1,2,3)
>>list2 = addToList(123,[]) >>tpl[2] = 4
>>list3 = addToList('a’) >>tpl
Output:TypeError: 'tuple'
>>print ("list1 = %s" % list1)
the object does not support item
>>print ("list2 = %s" % list2) assignment

>>print ("list3 = %s" % list3) There is an error because you can't

8 | www.simplilearn.com
Interview Guide

change the tuple 1 2 3 into 1 2 4. sum=add(10,20)


You have to completely reassign
print("Accessing doctstring
tuple to a new value.
method 1:",add._ _doc_ _)
print("Accessing doctstring
Q: What Is Docstring in Python? method 2:",end="")
help(add)
A: Docstrings are used in providing
documentation to various Python Output -
modules, classes, functions, and Accessing docstring method 1: This
methods. function adds two numbers.
Example - Accessing docstring method 2:
def add(a,b): Help on function add-in module
_ _main_ _:
" " "This function adds two
numbers." " " add(a, b)
sum=a+b This function adds two numbers.
return sum
sum=add(10,20) Q: How Do You Use Print()
print("Accessing doctstring Without the Newline?
method 1:",add._ _doc_ _)
A: The solution to this depends on the
print("Accessing doctstring Python version you are using.
method 2:",end="")
Python v2
help(add)
>>print(“Hi. ”),
Output -
>>print(“How are you?”)
Accessing docstring method 1: This
Output: Hi. How are you?
function adds two numbers.
Python v3
Accessing docstring method 2:
Help on function add-in module >>print(“Hi”,end=“ ”)
_ _main_ _: >>print(“How are you?”)
add(a, b) Output: Hi. How are you?
This function adds two numbers.

Q: How Do You Use the Split()


Q: What Is Docstring in Python? Function in Python?

A: Docstrings are used in providing A: The split() function splits a string


documentation to various Python into a number of strings based on
modules, classes, functions, and a specific delimiter.
methods.
Syntax -
Example -
string.split(delimiter, max)
def add(a,b):
Where:
" " "This function adds two
the delimiter is the character based
numbers." " "
on which the string is split. By
sum=a+b default it is space.
return sum max is the maximum number of

9 | www.simplilearn.com
Interview Guide

splits >>fun(1)
Example - >>fun(1,25,6)
>>var=“Red,Blue,Green,Orange” In the above code, * indicates that
there are multiple arguments of a
>>lst=var.split(“,”,2)
variable.
>>print(lst)
Output:
Q: What Are *args and *kwargs?
[‘Red’,’Blue’,’Green, Orange’]
Here, we have a variable var whose A: *args
values are to be split with commas. • I t is used in a function prototype
Note that ‘2’ indicates that only the to accept a varying number of
first two values will be split. arguments.
• It's an iterable object.
Q: Is Python Object-oriented or • Usage - def fun(*args)
Functional Programming?

A: Python is considered a multi- *kwargs


paradigm language. • I t is used in a function prototype
Python follows the object-oriented to accept the varying number of
paradigm keyworded arguments.
Python allows the creation of • It's an iterable object
objects and their manipulation • Usage - def fun(**kwargs):
through specific methods
fun(colour=”red”.units=2)
It supports most of the features
of OOPS such as inheritance and
polymorphism Q: “in Python, Functions Are First-
Python follows the functional class Objects.” What Do You
programming paradigm Infer from This?
Functions may be used as the first- A: It means that a function can be
class object treated just like an object. You
Python supports Lambda can assign them to variables, or
functions which are characteristic pass them as arguments to other
of the functional paradigm functions. You can even return
them from other functions.

Q: Write a Function Prototype


Q: What Is the Output Of: Print(_ _
That Takes a Variable Number
name_ _)? Justify Your Answer.
of Arguments.
A: _ _name_ _ is a special variable
A: The function prototype is as
that holds the name of the current
follows:
module. Program execution
def function_name(*list) starts from main or code with 0
>>def fun(*var): indentations. Thus, _ _name_ _ has
a value _ _main_ _ in the above
>> for i in var: case. If the file is imported from
print(i) another module, _ _name_ _ holds

10 | www.simplilearn.com
Interview Guide

the name of this module. 3])


Res_set [[1, 2, 3], [0, 1, 2], [1, 2, 3]]
Q: What Is a Numpy Array? Choose the correct option:
1. r es_set = train_set.append(test_
A: A numpy array is a grid of
set)
values, all of the same type, and
is indexed by a tuple of non- 2. r es_set = np.concatenate([train_
negative integers. The number of set, test_set]))
dimensions determines the rank of 3. r esulting_set = np.vstack([train_
the array. The shape of an array is set, test_set])
a tuple of integers giving the size
of the array along each dimension. 4. None of these
Here, options a and b would both
do horizontal stacking, but we
Q: What Is the Difference want vertical stacking. So, option c
Between Matrices and Arrays? is the right statement.

A: Matrices resulting_set = np.vstack([train_


set, test_set])
• A matrix comes from linear
algebra and is a two-dimensional
representation of data Q: How Would You Import a
• It comes with a powerful set of Decision Tree Classifier in
mathematical operations that Sklearn? Choose the Correct
allow you to manipulate the data in Option.
interesting ways
1. from sklearn.decision_tree
import DecisionTreeClassifier
Arrays
• An array is a sequence of objects 2. from sklearn.ensemble import
of similar data type DecisionTreeClassifier
• An array within another array forms 3. from sklearn.tree import
a matrix
DecisionTreeClassifier

4. None of these
Q: How Do You Get Indices of N
Maximum Values in a Numpy A: 3. from sklearn.tree import
Array? DecisionTreeClassifier

A: >>import numpy as np
>>arr=np.array([1, 3, 2, 4, 5]) Q: You Have Uploaded the Dataset
in Csv Format on Google
>>print(arr.argsort( ) [ -N: ][: : -1])
Spreadsheet and Shared It
Publicly. How Can You Access
Q: How Would You Obtain the This in Python?
Res_set from the Train_set and
A: We can use the following code:
the Test_set from Below?
>>link = https://docs.google.com/
A: >>train_set=np.array([1, 2, 3]) spreadsheets/d/...
>>test_set=np.array([[0, 1, 2], [1, 2, >>source = StringIO.

11 | www.simplilearn.com
Interview Guide

StringIO(requests.get(link). 1. pd.read_csv(“temp.csv”,
content)) compression=’gzip’)
>>data = pd.read_csv(source)
2. pd.read_csv(“temp.csv”,
dialect=’str’)
Q: What Is the Difference Between
the Two Data Series given 3. pd.read_csv(“temp.csv”,
Below? encoding=’utf-8)

df[‘Name’] and df.loc[:, 4. None of these


‘Name’], where: A: The error relates to the difference
between utf-8 coding and a
df = pd.DataFrame(['aa', 'bb',
Unicode.
'xx', 'uu'], [21, 16, 50, 33],
columns = ['Name', 'Age']) So option 3. pd.read_csv(“temp.
csv”, encoding=’utf-8) can correct
Choose the correct option: it.

1. 1 is the view of original


dataframe and 2 is a copy of Q. How Do You Set a Line Width in
original dataframe the Plot given Below?

2. 2 is the view of original


dataframe and 1 is a copy of
original dataframe

3. Both are copies of original


dataframe

4. Both are views of original


dataframe

A: 3. Both are copies of the original


dataframe.

>>import matplotlib.pyplot as plt


Q: You Get the Error “temp.Csv” >>plt.plot([1,2,3,4])
While Trying to Read a File
Using Pandas. Which of the >>plt.show()
Following Could Correct It? Choose the correct option:
Error: 1. I n line two, write plt.
plot([1,2,3,4], width=3)
Traceback (most recent 2. In line two, write plt.
call last): File "<input>", plot([1,2,3,4], line_width=3
line 1, in<module>
UnicodeEncodeError: 3. I n line two, write plt.
plot([1,2,3,4], lw=3)
'ascii' codec can't encode 4. None of these
character.
A: 3. In line two, write plt.
Choose the correct option: plot([1,2,3,4], lw=3)

12 | www.simplilearn.com
Interview Guide

Q. How Would You Reset the Index Numpy by the (N-1)Th Column.
of a Dataframe to a given List? A: This can be achieved by using
Choose the Correct Option. argsort() function. Let us take an
1. df.reset_index(new_index,) array X; the code to sort the (n-1)th
column will be x[x [: n-2].argsoft()]
2. df.reindex(new_index,)
The code is as shown below:
3. df.reindex_like(new_index,)
>>import numpy as np
4. None of these
>>X=np.
A: 3. df.reindex_like(new_index,) array([[1,2,3],[0,5,2],[2,3,4]])
>>X[X[:,1].argsort()]
Q. How Can You Copy Objects in Output:
Python? array([[1,2,3],[0,5,2],[2,3,4]])
A: The function used to copy objects
in Python are:
Q. How Do You Create a Series
copy.copy for shallow copy and
from a List, Numpy Array, and
copy.deepcopy() for deep copy Dictionary?
Looking forward to a career as A: The code is as shown:
a Data Scientist? Check out the
>> #Input
Data Science with Python Training
Course and get certified today. >>import numpy as np
>>import pandas as pd
Q. What Is the Difference Between >>mylist =
range() and xrange() Functions list('abcedfghijklmnopqrstuvwxyz’)
in Python? >>myarr = np.arange(26)
A: range() >>mydict = dict(zip(mylist, myarr))
range returns a Python list object >> #Solution
xrange() >>ser1 = pd.Series(mylist)
xrange returns an xrange object >>ser2 = pd.Series(myarr)
>>ser3 = pd.Series(mydict)
Q. How Can You Check Whether a >>print(ser3.head())
Pandas Dataframe Is Empty or
Not?
Q. How Do You Get the Items Not
A: The attribute df.empty is used Common to Both Series a and
to check whether a pandas data Series B?
frame is empty or not.
A: >> #Input
>>import pandas as pd
>>import pandas as pd
>>df=pd.DataFrame({A:[]})
>>ser1 = pd.Series([1, 2, 3, 4, 5])
>>df.empty
>>ser2 = pd.Series([4, 5, 6, 7, 8])
Output: True
>> #Solution
>>ser_u = pd.Series(np.
Q. Write a Code to Sort an Array in union1d(ser1, ser2)) # union

13 | www.simplilearn.com
Interview Guide

>>ser_i = pd.Series(np. >> #Solution


intersect1d(ser1, ser2)) # intersect
>>sum((p - q)**2)**.5
>>ser_u[~ser_u.isin(ser_i)]
>> #Solution using func
>>np.linalg.norm(p-q)
Q. How Do You Keep Only the Top You can see that the Euclidean
Two Most Frequent Values as It distance can be calculated using
Is and Replace Everything Else two ways.
as ‘other’ in a Series?
A: >> #Input
Q. How Do You Reverse the Rows
>>import pandas as pd of a Data Frame?
>>np.random.RandomState(100) >> #Input
>>ser = pd.Series(np.random. >>df = pd.DataFrame(np.
randint(1, 5, [12])) arange(25).reshape(5, -1))
>> #Solution >> #Solution
>>print("Top 2 Freq:", ser.value_ >>df.iloc[::-1, :]
counts())
>>ser[~ser.isin(ser.value_counts().
index[:2])] = 'Other’ Q. If You Split Your Data into Train/
Test Splits, Is It Possible to over
>>ser
Fit Your Model?
A: Yes. One common beginner
Q. How Do You Find the Positions mistake is re-tuning a model or
of Numbers That Are Multiples training new models with different
of Three from a Series? parameters after seeing its
performance on the test set.
A: >> #Input
>>import pandas as pd
Q. Which Python Library Is Built on
>>ser = pd.Series(np.random.
randint(1, 10, 7))
Top of Matplotlib and Pandas
to Ease Data Plotting?
>>ser
A: Seaborn is a Python library built
>> #Solution on top of matplotlib and pandas
>>print(ser) to ease data plotting. It is a data
visualization library in Python that
>>np.argwhere(ser % 3==0) provides a high-level interface
for drawing statistical informative
graphs.
Q. How Do You Compute the
Euclidean Distance Between
Two Series?
A: The code is as shown:
>> #Input
>>p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8,
9, 10])
>>q = pd.Series([10, 9, 8, 7, 6, 5, 4,
3, 2, 1])

14 | www.simplilearn.com
Interview Guide

BREAKING INTO PYTHON


Cracking a job interview requires careful preparation apart from the
right blend of skills and knowledge. There are a number of emerging
job opportunities that demand proficiency in Python. As recruiters hunt
for professionals with relevant skills, you need to ensure that you have a
thorough knowledge of Python fundamentals. You can enroll in Simplilearn’s
Data Science with Python course to gain expertise in this language and
become a potential candidate for your next job interview.

INDIA USA
Simplilearn Solutions Pvt Ltd. Simplilearn Americas, Inc.
# 53/1 C, Manoj Arcade, 24th Main, 201 Spear Street, Suite 1100,
Harlkunte San Francisco, CA 94105
2nd Sector, HSR Layout United States
Bangalore: 560102 Phone No: +1-844-532-7688
Call us at: 1800-212-7688

www.simplilearn.com
15 | www.simplilearn.com

You might also like