Python Interview Questions
Python Interview Questions
Question 12: What Packages in the Standard Library, Useful for Data Science Work,
Do You Know?
When Guido van Rossum created Python in the 1990s, it wasn’t built for data science. Yet,
today, Python is the leading language for machine learning, predictive analytics, statistics,
and simple data analytics.
This is because Python is a free and open-source language that data professionals could easily
use to develop tools that would help them complete data tasks more efficiently.
The following packages in the Python Standard Library are very handy for data science
projects:
NumPy
NumPy (or Numerical Python) is one of the principal packages for data science applications.
It’s often used to process large multidimensional arrays, extensive collections of high-level
mathematical functions, and matrices. Implementation methods also make it easy to conduct
multiple operations with these objects .
T here have been many improvements made over the last year that have resolved several bugs
and compatibility issues. NumPy is popular because it can be used as a highly efficient
multi-dimensional container of generic data. It’s also an excellent library as it makes data
analysis simple by processing data faster while using a lot less code than lists.
Pandas
Pandas is a Python library that provides highly flexible and powerful tools and high-level
data structures for analysis. Pandas is an excellent tool for data analytics because it can
translate highly complex operations with data into just one or two commands.
Pandas come with a variety of built-in methods for combining, filtering, and grouping data. It
also boasts time-series functionality that is closely followed by remarkable speed indicators.
SciPy
SciPy is another outstanding library for scientific computing. It’s based on NumPy and was
created to extend its capabilities. Like NumPy, SciPy’s data structure is also a
multidimensional array that’s implemented by NumPy.
The SciPy package contains powerful tools that help solve tasks related to integral calculus,
linear algebra, probability theory, and much more .
Recently, this Python library went through some major build improvements in the form of
continuous integration into multiple operating systems, methods, and new functions.
Optimizers were also updated, and several new BLAS and LAPACK functions were
wrapped.
Question 13: What does this stuff mean: *args, **kwargs? And why would we use it?
Use *args when we aren't sure how many arguments are going to be passed to a function, or
if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we
don't know how many keyword arguments will be passed to a function, or it can be used to
pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a
convention, you could also use *bob and **billy but that would not be wise.
Here is a little illustration:
def f(*args,**kwargs): print(args, kwargs)
l = [1,2,3]
t = (4,5,6)
d = {'a':7,'b':8,'c':9}
f()
f(1,2,3) # (1, 2, 3) {}
f(1,2,3,"groovy") # (1, 2, 3, 'groovy') {}
f(a=1,b=2,c=3) # () {'a': 1, 'c': 3, 'b': 2}
f(a=1,b=2,c=3,zzz="hi") # () {'a': 1, 'c': 3, 'b': 2, 'zzz': 'hi'}
f(1,2,3,a=1,b=2,c=3) # (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
f(*l,**d) # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8}
f(*t,**d) # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8}
f(1,2,*t) # (1, 2, 4, 5, 6) {}f(q="winning",**d)
# () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}f(1,2,*t,q="winning",**d)
# (1, 2, 4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}
def f2(arg1,arg2,*args,**kwargs):
print(arg1,arg2, args, kwargs)f2(1,2,3)
# 1 2 (3,) {}f2(1,2,3,"groovy") # 1 2 (3, 'groovy')
{}f2(arg1=1,arg2=2,c=3)
# 1 2 () {'c': 3}f2(arg1=1,arg2=2,c=3,zzz="hi") # 1 2 () {'c': 3, 'zzz':
'hi'}f2(1,2,3,a=1,b=2,c=3)
# 1 2 (3,) {'a': 1, 'c': 3, 'b': 2}
f2(*l,**d) # 1 2 (3,) {'a': 7, 'c': 9, 'b': 8}f2(*t,**d)
# 4 5 (6,) {'a': 7, 'c': 9, 'b': 8}f2(1,2,*t) # 1 2 (4, 5, 6)
{}f2(1,1,q="winning",**d)
# 1 1 () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}f2(1,2,*t,q="winning",**d)
# 1 2 (4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}
class B(A):
def go(self):
super(B, self).go()
print("go B go!")
class C(A):
def go(self): super(C, self).go() print("go C go!") def stop(self): super(C,
self).stop() print("stop C stop!")
class D(B,C): def go(self): super(D, self).go() print("go D go!") def stop(self):
super(D, self).stop() print("stop D stop!") def pause(self): print("wait D wait!")
class E(B,C): pass
a = A()b = B()c = C()d = D()e = E()
# specify output from here onwards
a.go()b.go()c.go()d.go()e.go()
a.stop()b.stop()c.stop()d.stop()e.stop()
a.pause()b.pause()c.pause()d.pause()e.pause()
class Node(object):
def __init__(self,sName):
self._lChildren = []
self.sName = sName
def __repr__(self):
def append(self,*args,**kwargs)
self._lChildren.append(*args,**kwargs) def print_all_1(self):
print(self) for oChild in self._lChildren: oChild.print_all_1()
def print_all_2(self):
def gen(o):
lAll = [o,] while lAll:
oNext = lAll.pop(0) lAll.extend(oNext._lChildren)
yield oNext for oNode in gen(self): print(oNode)
oRoot = Node("root")oChild1 = Node("child1")oChild2 = Node("child2")oChild3 =
Node("child3")oChild4 = Node("child4")oChild5 = Node("child5")oChild6 =
Node("child6")oChild7 = Node("child7")oChild8 = Node("child8")oChild9 =
Node("child9")oChild10 = Node("child10")
oRoot.append
(oChild1)oRoot.append(oChild2)oRoot.append(oChild3)oChild1.append(oChild4)oChild1.ap
pend(oChild5)oChild2.append(oChild6)oChild4.append(oChild7)oChild3.append(oChild8)o
Child3.append(oChild9)oChild6.append(oChild10)
# specify output from here onwards
oRoot.print_all_1()oRoot.print_all_2
()AnsweroRoot.print_all_1() prints:<Node 'root'>
<Node 'child1'>
<Node 'child4'>
<Node 'child7'>
<Node 'child5'>
<Node 'child2'>
<Node 'child6'>
<Node 'child10'>
<Node 'child3'>
<Node 'child8'>
<Node 'child9'>
oRoot.print_all_2()
prints:<Node 'root'>
<Node 'child1'><Node 'child2'>
<Node 'child3'><Node 'child4'>
<Node 'child5'><Node 'child6'>
<Node 'child8'><Node 'child9'><Node 'child7'>
<Node 'child10'>
Question 16: Describe Python's garbage collection mechanism in brief.
AnswerA lot can be said here. There are a few main points that you should mention:Python
maintains a count of the number of references to each object in memory. If a reference count
goes to zero then the associated object is no longer live and the memory allocated to that
object can be freed up for something elseoccasionally things called "reference cycles"
happen. The garbage collector periodically looks for these and cleans them up. An example
would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1.
If o1 and o2 are not referenced by anything else then they shouldn't be live. But each of them
has a reference count of 1.Certain heuristics are used to speed up garbage collection. For
example, recently created objects are more likely to be dead. As objects are created, the
garbage collector assigns them to generations. Each object gets one generation, and younger
generations are dealt with first.This explanation is CPython specific.
Question 16: Place the following functions below in order of their efficiency. They all
take in a list of numbers between 0 and 1. The list can be quite long. An example input
list would be [random.random() for i in range(100000)]. How would you prove that your
answer is correct?
def f1(lIn): l1 = sorted(lIn)
l2 = [i for i in l1 if i<0.5]
return [i*i for i in l2]
def f2(lIn): l1 = [i for i in lIn if i<0.5]
l2 = sorted(l1)
return [i*i for i in l2]
def f3(lIn): l1 = [i*i for i in lIn] l2 = sorted(l1)
return [i for i in l1 if i<(0.5*0.5)]
Most to least efficient: f2, f1, f3. To prove that this is the case, you would want to profile
your code. Python has a lovely profiling package that should do the trick.import cProfilelIn =
[random.random() for i in range(100000)]cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')
For completion's sake, here is what the above profile outputs:>>> cProfile.run('f1(lIn)')
4 function calls in 0.045 seconds
Ordered by: standard name ncalls tottime percall cumtime percall
filename:lineno(function)
1 0.009 0.009 0.044 0.044 <stdin>:1(f1) 1 0.001 0.001 0.045 0.045
<string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects} 1 0.035 0.035 0.035 0.035 {sorted}
>>> cProfile.run('f2(lIn)') 4 function calls in 0.024 seconds
Ordered by: standard name ncalls tottime percall cumtime percall
filename:lineno(function) 1 0.008 0.008 0.023 0.023
<stdin>:1(f2) 1 0.001 0.001 0.024 0.024
<string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects} 1 0.016 0.016 0.016 0.016 {sorted}
>>> cProfile.run('f3(lIn)') 4 function calls in 0.055 seconds
Ordered by: standard name ncalls tottime percall cumtime percall
filename:lineno(function) 1 0.016 0.016 0.054 0.054
<stdin>:1(f3) 1 0.001 0.001 0.055 0.055
<string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects} 1 0.038 0.038 0.038 0.038 {sorted}
Question 21: What is the output of print str if str = 'Hello World!'?
Question 22: What is the output of print str[0] if str = 'Hello World!'?
It will print the first character of the string. The output would be H.
Question 23: What is the output of print str[2:5] if str = 'Hello World!'?
It will print characters starting from 3rd to 5th. The output would be llo.
Question 24: What is the output of print str[2:] if str = 'Hello World!'?
It will print characters starting from 3rd character. The output would be llo World!.
Question 25: What is the output of print str * 2 if str = 'Hello World!'?
It will print the string two times. The output would be Hello World! Hello World!.
Question 26: What is the output of print str + "TEST" if str = 'Hello World!'?
Question 27: What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
It will print complete list. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003].
Question 28: What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
Question 29: What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2
]?
It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].
It will print elements starting from 3rd element. Output would be [2.23, 'john',
70.200000000000003].
Question 31: What is the output of print tinylist * 2 if tinylist = [123, 'john']?
It will print list two times. Output would be [123, 'john', 123, 'john'].
Question 32: What is the output of print list1 + list2, if list1 = [ 'abcd', 786 , 2.23, 'john',
70.2 ] and ist2 = [123, 'john']?I
t will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Question 33: What are tuples in Python?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
Question 34: What is the difference between tuples and lists in Python?
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.
Question 35: What is the output of print tuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2
)?
It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003).
Question 36: What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 )?
It will print the first element of the tuple. The output would be abcd.
Question 37: What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 )?
It will print elements starting from 2nd till 3rd. The output would be (786, 2.23).
Question 38: What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 )?
It will print elements starting from the 3rd element. The output would be (2.23, 'john',
70.200000000000003).
Question 39: What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?
It will print tuple two times. The output would be (123, 'john', 123, 'john').
Question 40: What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23,
'john', 70.2 ) and tinytuple = (123, 'john')?
It will print concatenated tuples. Output would be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
Question 41: What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Question 42: How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).dict = {}dict['one'] = "This is one"dict[2] = "This is two"tinydict =
{'name': 'john','code':6734, 'dept': 'sales'}
Question 43: How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.print
dict.keys() # Prints all the keys
Question 44: How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.print
dict.values() # Prints all the values
Question 128: Name the python Library used for Machine learning.
Scikit-learn python Library used for Machine learning
Question 129: What does pass operation do?
Pass indicates that nothing is to be done i.e. it signifies a no operation.
Question 130: Name the tools that python uses to find bugs (if any).
Pylint and pychecker.
Question 131: Write a function to give the sum of all the numbers in the list?
Sample list − (100, 200, 300, 400, 0, 500)
Expected output − 1500
Question 132: Program for the sum of all the numbers in the list is −
def sum(numbers):
total = 0 for num in numbers:
total+=num print(''Sum of the numbers: '
', total)sum((100, 200, 300, 400, 0, 500))
We define a function ‘sum’ with numbers as a parameter. The in for loop we store the sum of
all the values of the list.
Question 133: Write a program in Python to reverse a string without using the inbuilt
function reverse string?
Program to reverse a string is given below −
def string_reverse(str1):
rev_str = ' '
index = len(str1) #defining index as length of string.
while(index>0):
rev_str = rev_str + str1[index-1]
index = index-1
return(rev_str)
print(string_reverse('1tniop'))
First, we declare a variable to store the reversed string. Then using while loop and indexing
of string (index is calculated by string length) we reverse the string. While loop starts when
the index is greater than zero. The index is reduced to value 1 each time. When the index
reaches zero we obtain the reverse of a string.
Question 134: Write a program to test whether the number is in the defined range or
not?
Program is −
def test_range(num): if num in range(0, 101):
print(''%s is in range''%str(num))
else:
print(''%s is not in range''%str(num))
Output −
test_range(101)
101 is not in the rangeTo test any number in a particular range we make use of the method
‘if.. in’ and else condition.