Python Interview Questions and Answers _ myTectra
Python Interview Questions and Answers _ myTectra
com
Login / Register
SEARCH
PREVIOUS ARTICLE
SAP KM Interview Questions and Answers
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 1/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
BY SONIA FERNANDES
Q1).What is Python?
Ans1: Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it h
as fewer syntactical constructions than other languages.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 2/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Numbers
String
List
Tuple
Dictionary
Q11).What is the output of print list if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?
Ans11: It will print concatenated lists. Output would be [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ].
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 3/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q12).What is the output of print list[0] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?
Ans12: It will print first element of the list. Output would be abcd.
Q13).What is the output of print list[1:3] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?
Ans13: It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].
Q14).What is the output of print list[2:] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?
Ans14: It will print elements starting from 3rd element. Output would be [2.23, ‘john’, 70.200000000000003].
Q16).What is the output of print list + tinylist * 2 if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ] and tinylist =
[123, ‘john’]?
Ans16: It will print concatenated lists. Output would be [‘abcd’, 786, 2.23, ‘john’, 70.2, 123, ‘john’, 123, ‘john’].
Q19).What is the output of print tuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?
Ans19:It will print complete tuple. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003).
Q20).What is the output of print tuple[0] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?
Ans20: It will print first element of the tuple. Output would be abcd.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 4/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q21).What is the output of print tuple[1:3] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?
Ans21: It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).
Q22).What is the output of print tuple[2:] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?
Ans22: It will print elements starting from 3rd element. Output would be (2.23, ‘john’, 70.200000000000003).
Q24).What is the output of print tuple + tinytuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2) and
tinytuple = (123, ‘john’)?
Ans24: It will print concatenated tuples. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123,
‘john’).
Q27).How will you get all the keys from the dictionary?
Ans27: Using dictionary.keys() function, we can get all the keys from the dictionary object.
print dict.keys() # Prints all the keys
Q28).How will you get all the values from the dictionary?
Ans28: Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 5/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 6/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q42).How will you convert a single character to its integer value in python?
Ans42: ord(x) − Converts a single character to its integer value.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 7/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q55).How will you set the starting value in generating random numbers?
Ans55: seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling
any other random module function. Returns None.
Q59).How will you check in a string that all characters are digits?
Ans59: isdigit() − Returns true if string contains only digits and false otherwise.
Q60).How will you check in a string that all characters are in lowercase?
Ans60: islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and
false otherwise.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 8/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q61).How will you check in a string that all characters are numerics?
Ans61: isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.
Q62).How will you check in a string that all characters are whitespaces?
Ans62:isspace() − Returns true if string contains only whitespace characters and false otherwise.
Q64).How will you check in a string that all characters are in uppercase?
Ans64: isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and
false otherwise.
Q67).How will you get a space-padded string with the original string left-justified to a total of width
columns?
Ans67: just(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width
columns.
Q70).How will you get the max alphabetical character from the string?
Ans70: max(str) − Returns the max alphabetical character from the string str.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 9/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
0Q71).How will you get the min alphabetical character from the string?
Ans71: min(str) − Returns the min alphabetical character from the string str.
Q72).How will you replaces all occurrences of old substring in string with new string?
Ans72: replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max
occurrences if max given.
Q73).How will you remove all leading and trailing whitespace in string?
Ans73:strip([chars]) − Performs both lstrip() and rstrip() on string.
Q77).How will you check in a string that all characters are decimal?
Ans77: isdecimal() − Returns true if a unicode string contains only decimal characters and false
otherwise.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 10/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 11/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q97).Name ve modules that are included in python by default (many people come searching for
this, so I included some more examples of modules which are often used)
Ans97:
datetime (used to manipulate date and time)
re (regular expressions)
urllib, urllib2 (handles many HTTP things)
string (a collection of di erent groups of strings for example all lower_case letters etc)
itertools (permutations, combinations and other useful iterables)
ctypes (from python docs: create and manipulate C data types in Python)
email (from python docs: A package for parsing, handling, and generating email messages)
__future__ (Record of incompatible language changes. like division operator is di erent and much
better when imported from __future__)
sqlite3 (handles database of SQLite type)
unittest (from python docs: Python unit testing framework, based on Erich Gamma’s JUnit and
Kent Beck’s Smalltalk testing framework)
xml (xml support)
logging (de nes logger classes. enables python to log details on severity level basis)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 12/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
1 class abc():
2 pass
Q101).What is a docstring?
function_name.__doc__
it is declared as:
1 def function_name():
2 “””your docstring”””
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 13/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Writing documentation for your progams is a good habit and makes the code more understandable and
reusable.
Ans102: Creating a list by doing some operation over data that can be accessed using an iterator. For
eg:
2 [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80
3 >>>
Q103).What is map?
Ans103: map executes the function given as the rst argument on all the elements of the iterable given
as the second argument. If the function given takes in more than 1 arguments, then many iterables are
given. #Follow the link to know more similar functions
For eg:
1 >>>a=’ayush’
2 >>>map(ord,a)
3
map(…)
4
map(function, sequence[, sequence, …]) -> list
5
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 14/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
#Python Docs
Ans104:A tuple is immutable i.e. can not be changed. It can be operated on only. But a list is mutable.
Changes can be done internally to it.
The methods/functions provided with each types are also di erent. Check them out yourself.
Q105).Using various python modules convert the list a to generate the output ‘one, two, three’
Ans105:
2 Ans: “, “.join(a)
1 >>>help(str.join)
2 Help on method_descriptor:
3 join(…)
1 word = ‘abcdefghij’
1 word = ‘word’
2 print word.__len__()
Ans107:
1 word = ‘word’
2 print len(word)
Ans108:
1 try:
3 print f.read()
4 except IOError:
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 16/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
1 a=1
2 a, b = a+1, a+1
3 print a
4 print b
Ans109:
2
2
The second line is a simultaneous declaration i.e. value of new a is not used when doing b=a+1.
1 a,b = b,a
Ans110:
A bad solution would be to iterate over the list and checking for copies somehow and then remove
them!
1 a = [1,2,2,3]
2 list(set(a))
set is another type available in python, where copies are not allowed. It also has some good functions
available used in set operations ( like union, di erence ).
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 17/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Q111).Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each
word. for example
Ans111:
2 a = {}
3 for i in words:
4 try:
5 a[i] += 1
8 return a
10 >>> a=’1,3,2,4,5,3,2,1,4,3,2′.split(‘,’)
11 >>> a
12 [‘1’, ‘3’, ‘2’, ‘4’, ‘5’, ‘3’, ‘2’, ‘1’, ‘4’, ‘3’, ‘2’]
13 >>> dic(a)
2 data = {}
3 for i in words:
4 data[i] = data.get(i, 0) + 1
5 return data
7 >>> a
8 [‘1’, ‘3’, ‘2’, ‘4’, ‘5’, ‘3’, ‘2’, ‘1’, ‘4’, ‘3’, ‘2’]
9 >>> dic(a)
PS: Since the collections module (which gives you the defaultdict) is written in python, I would not
recommend using it. The normal dict implementation is in C, it should be much faster. You can
use timeit module to check for comparing the two.
So, David and I have saved you the work to check it. Check the les on github. Change the data le to
test di erent data.
3
>>> a=”
4
>>> print “‘The list is
5 empty'” if len(a)==0 else “‘The list is not empty'”
7 >>> a=’asd’
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 19/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Ans113:
1 try:
2 import mechanize as me
3 except ImportError:
4 import urllib as me
Q114).Print the length of each line in the le ‘ le.txt’ not including any whitespaces at the end of
the lines.
Ans114:
2 print len(f1.readline().rstrip())
rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs (whitespace
characters).
Q115). Print the sum of digits of numbers starting from 1 to 100 (inclusive of both)
Ans115:
1 print sum(range(1,101))
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 20/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
range() returns a list to the sum function containing all the numbers from 1 to 100. Please see that the
range function does not include the end given (101 here).
xrange() returns an iterator rather than a list which is less heavy on the memory.
Q116).Create a new list that converts the following list of number strings to a list of numbers.
num_strings = [‘1′,’21’,’53’,’84’,’50’,’66’,’7′,’38’,’9′]
Ans116:
use a list comprehension
#num_strings should not contain any non-integer character else ValueError would be raised. A try-
catch block can be used to notify the user of this.
Q117).Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]
Ans117:
1 >>> odd=[]
2 >>> even=[]
3 >>> for i in n:
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 21/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Though if only one of the lists were requires, using list comprehension we could make:
But using this approach if both lists are required would not be e cient since this would iterate the list
two times.!
nums = [1,5,2,10,3,45,23,1,4,7,9]
Python uses TimSort for applying this function. Check the link to know more.
Q119).Write a for loop that prints all elements of a list and their position in the list.
Printing using String formatting
Ans119:
4 0 -> 4
5 1 -> 7
6 2 -> 3
7 3 -> 2
8 4 -> 5
9 5 -> 9
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 22/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
#OR
4 …. print i+1,’–>’,asd[i]
6 1 –> 4
7 2 –> 7
8 3 –> 3
9 4 –> 2
10 5 –> 5
11 6 –> 9
Q120).The following code is supposed to remove numbers less than 5 from list n, but there is a
bug. Fix the bug.
Ans120:
1 n = [1,2,5,10,3,100,9,24]
3 for e in n:
4 if e<5:
5 n.remove(e)
6 print n
## after e is removed, the index position gets disturbed. Instead it should be:
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 23/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
1 a=[]
2 for e in n:
3 if e >= 5:
4 a.append(e)
5 n=a
OR use lter
1 def func(x,*y,**z):
2 …. print z
4 func(1,2,3)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 24/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
{} #Empty Dictionay
Ans122:
a=5
b=9
1 class C(object):
2 …. def__init__(self):
3 …. self.x =1
5 c=C()
6 print c.x
7 print c.x
8 print c.x
9 print c.x
Ans123: All the outputs will be 1, since the value of the the object’s attribute(x) is never changed.
1
1
1
1
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 25/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
7 print n
Ans124. This would result in a NameError. The variable n is local to function func and can’t be accessesd
outside. So, printing it won’t be possible.
Edit: An extra point for interviews given by Shane Green and Peter: “””Another thing is that mutable
types should never be used as default parameter values. Default parameter value expressions are only
evaluated once, meaning every invocation of that method shares the same default value. If one
invocation that ends up using the default value modi es that value–a list, in this case–it will forever be
modi ed for all future invocations. So default parameter values should limited to primitives, strings, and
tuples; no lists, dictionaries, or complex object instances.”””
Reference: Default argument values
Ans125:
1. n = 1
print n++ ## no such operator in python (++)
2. n = 1
print ++n ## no such operator in python (++)
3. n = 1
print n += 1 ## will work
4. int n = 1
print n = n+1 ##will not work as assignment can not be done in print command like this
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 26/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
5. n =1
n = n+1 ## will work
Ans126: It is somewhat more complicated than I have written here (Thanks David for pointing).
Explaining all here won’t be possible. Some good links that would really make you understand how
things are:
Stackover ow
Ans127:
1 ”.join(s.split())
OR
1 lter(lambda x: x != ‘ ‘, s)
Ans128: seems like a string is being concatenated. Nothing much can be said without knowing types of
variables a, b, c. Also, if all of the a, b, c are not of type string, TypeError would be raised. This is because
of the string constants (‘[‘ , ‘]’) used in the statement.
1 def append_s(words):
2 new_words=[]
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 27/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
4 new_words.append(word + ‘s’)
5 return new_words
8 print word
Ans129: The above code adds a trailing s after each element of the list.
def append_s(words):
return [i+’s’ for i in words] ## another list comprehension
Q130).If given the rst and last names of bunch of employees how would you store it and what
datatype?
Q131).What is Python really? You can (and are encouraged) make comparisons to other technologies in
your answer
Python is an interpreted language. That means that, unlike languages like Cand its variants, Python does not
need to be compiled before it is run. Other interpreted languages include PHP and Ruby.
Python is dynamically typed, this means that you don’t need to state the types of variables when you
declare them or anything like that. You can do things like x=111and then x=”I’m a string”without error
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 28/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Python is well suited to object orientated programming in that it allows the de nition of classes along with
composition and inheritance. Python does not have access speci ers (like C++’s public, private), the
justi cation for this point is given as “we are all adults here”
In Python, functions are rst-class objects. This means that they can be assigned to variables, returned from
other functions and passed into functions. Classes are also rst class objects
Writing Python code is quick but running it is often slower than compiled languages. Fortunately, Python
allows the inclusion of C based extensions so bottlenecks can be optimised away and often are.
The numpypackage is a good example of this, it’s really quite quick because a lot of the number crunching it
does isn’t actually done by Python
Python nds use in many spheres – web applications, automation, scienti c modelling, big data
applications and many more. It’s also often used as “glue” code to get other languages and components to play
nice.
Python makes di cult things easy so programmers can focus on overriding algorithms and structures rather
than nitty-gritty low level details.
If you are applying for a Python position, you should know what it is and why it is so gosh-darn cool.
And why it isn’t o.O
def print_directory_contents(sPath):
“””
contained directories.
“””
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 29/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
ll_this_in
import os
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)
Be consistent with your naming conventions. If there is a naming convention evident in any sample code,
stick to it. Even if it is not the naming convention you usually use
Recursive functions need to recurse and Make sure you understand how this happens so that you avoid
bottomless callstacks
We use the osmodule for interacting with the operating system in a way that is cross platform. You could
say sChildPath = sPath + ‘/’ + sChild but that wouldn’t work on windows
Familiarity with base packages is really worthwhile, but don’t break your head trying to memorize
everything, Google is your friend in the workplace!
Ask questions if you don’t understand what the code is supposed to do
KISS! Keep it Simple, Stupid!
Q133).
Looking at the below code, write down the nal values of A0, A1, …An.
A0 = dict(zip((‘a’,’b’,’c’,’d’,’e’),(1,2,3,4,5)))
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 30/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
A1 = range(10)
A4 = [i for i in A1 if i in A3]
If you dont know what zip is don’t stress out. No sane employer will expect you to memorize the
standard library. Here is the output of help(zip).
zip(…)
Return a list of tuples, where each tuple contains the i-th element
If that doesn’t make sense then take a few minutes to gure it out however you choose to.
Ans133: A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
1. List comprehension is a wonderful time saver and a big stumbling block for a lot of people
2. If you can read them, you can probably write them down
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 31/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
3. Some of this code was made to be deliberately weird. You may need to work with some weird people
Q134).Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in
a parallel way.
Ans134: Python doesn’t allow multi-threading in the truest sense of the word. It has a multi-threading
package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use
it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of
your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the
GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads
are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL
passing adds overhead to execution. This means that if you want to make your code run faster then
using the threading package often isn’t a good idea.
There are reasons to use Python’s threading package. If you want to run some things simultaneously,
and e ciency is not a concern, then it’s totally ne and convenient. Or if you are running code that
needs to wait for something (like some IO) then it could make a lot of sense. But the threading library
won’t let you use extra CPU cores.
Multi-threading can be outsourced to the operating system (by doing multi-processing), some external
application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls
(eg: you could have your Python code call a C function that does the expensive multi-threaded stu ).
Because the GIL is an A-hole. Lots of people spend a lot of time trying to nd bottlenecks in their fancy
Python multi-threaded code before they learn what the GIL is.
Ans135: Version control! At this point, you should act excited and tell them how you even use Git (or
whatever is your favorite) to keep track of correspondence with Granny. Git is my preferred version
control system, but there are others, for example subversion.
Because code without version control is like co ee without a cup. Sometimes we need to write once-
o throw away scripts and that’s ok, but if you are dealing with any signi cant amount of code, a
version control system will be a bene t. Version Control helps with keeping track of who made what
change to the code base; nding out when bugs were introduced to the code; keeping track of versions
and releases of your software; distributing the source code amongst team members; deployment and
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 32/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
certain automations. It allows you to roll your code back to before you broke it which is great on its
own. Lots of stu . It’s just great.
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
f(2)
f(3,[3,2,1])
f(3)
Ans136:
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
Hu?
The rst function call should be fairly obvious, the loop appends 0 and then 1 to the empty list, l. l is a
name for a variable that points to a list stored in memory.
The second call starts o by creating a new list in a new block of memory. l then refers to this new list. It
then appends 0, 1 and 4 to this new list. So that’s great.
The third function call is the weird one. It uses the original list stored in the original memory block. That
is why it starts o with 0 and 1.
l_mem = []
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 33/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
for i in range(2):
l.append(i*i)
print(l) # [0, 1]
for i in range(3):
l.append(i*i)
print(l) # [3, 2, 1, 0, 1, 4]
for i in range(3):
l.append(i*i)
print(l) # [0, 1, 0, 1, 4]
Ans137:Monkey patching is changing the behaviour of a function or object after it has already been
de ned. For example:
import datetime
Most of the time it’s a pretty terrible idea – it is usually best if things act in a well-de ned way. One
reason to monkey patch would be in testing. The mock package is very useful to this end.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 34/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
It shows that you understand a bit about methodologies in unit testing. Your mention of monkey
avoidance will show that you aren’t one of those coders who favor fancy code over maintainable code
(they are out there, and they suck to work with). Remember the principle of KISS? And it shows that
you know a little bit about how Python works on a lower level, how functions are actually stored and
called and suchlike.
PS: it’s really worth reading a little bit about mock if you haven’t yet. It’s pretty useful.
Q138).What does this stu mean: *args, **kwargs? And why would we use it?
Ans138: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. **kwargsis used when we dont 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 identi ers args and kwargs are a convention, you could also
use *bob and **billy but that would not be wise.
l = [1,2,3]
t = (4,5,6)
d = {‘a’:7,’b’:8,’c’:9}
f()
f(1,2,3) # (1, 2, 3) {}
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 35/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
f(1,2,*t) # (1, 2, 4, 5, 6) {}
f2(1,2,3) # 1 2 (3,) {}
f2(arg1=1,arg2=2,c=3) # 1 2 () {‘c’: 3}
f2(1,2,*t) # 1 2 (4, 5, 6) {}
Why Care?
Sometimes we will need to pass an unknown number of arguments or keyword arguments into a
function. Sometimes we will want to store arguments or keyword arguments for later use. Sometimes
it’s just a time saver.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 36/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
These are decorators. A decorator is a special kind of function that either takes a function and returns a
function, or takes a class and returns a class. The @ symbol is just syntactic sugar that allows you to
decorate something in a way that’s easy to read.
@my_decorator
def my_func(stu ):
do_things
Is equivalent to
def my_func(stu ):
do_things
my_func = my_decorator(my_func)
Actual Answer:
The decorators @classmethod, @staticmethod and @property are used on functions de ned within
classes. Here is how they behave:
class MyClass(object):
def __init__(self):
def normal_method(*args,**kwargs):
print(“calling normal_method({0},{1})”.format(args,kwargs))
@classmethod
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 37/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
def class_method(*args,**kwargs):
print(“calling class_method({0},{1})”.format(args,kwargs))
@staticmethod
def static_method(*args,**kwargs):
print(“calling static_method({0},{1})”.format(args,kwargs))
@property
def some_property(self,*args,**kwargs):
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
self._some_property = args[0]
@property
def some_other_property(self,*args,**kwargs):
return self._some_other_property
o = MyClass()
# undecorated methods work like normal, they get the current instance (self) as the rst argument
o.normal_method
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 38/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
o.normal_method()
o.normal_method(1,2,x=3,y=4)
o.class_method
o.class_method()
o.class_method(1,2,x=3,y=4)
# static methods have no arguments except the ones you pass in when you call them
o.static_method
o.static_method()
# static_method((),{})
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 39/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
o.static_method(1,2,x=3,y=4)
# properties are a way of implementing getters and setters. It’s an error to explicitly call them
# “read only” attributes can be speci ed by creating a getter without a setter (as in
some_other_property)
o.some_property
o.some_property()
o.some_other_property
# ‘VERY nice’
# o.some_other_property()
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 40/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
o.some_property = “groovy”
o.some_property
# ‘groovy’
o.some_other_property
# ‘VERY nice’
class A(object):
def go(self):
print(“go A go!”)
def stop(self):
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 41/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
print(“stop A stop!”)
def pause(self):
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!”)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 42/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
def pause(self):
print(“wait D wait!”)
a = A()
b = B()
c = C()
d = D()
e = E()
a.go()
b.go()
c.go()
d.go()
e.go()
a.stop()
b.stop()
c.stop()
d.stop()
e.stop()
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 43/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
a.pause()
b.pause()
c.pause()
d.pause()
e.pause()
Ans140:
a.go()
# go A go!
b.go()
# go A go!
# go B go!
c.go()
# go A go!
# go C go!
d.go()
# go A go!
# go C go!
# go B go!
# go D go!
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 44/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
e.go()
# go A go!
# go C go!
# go B go!
a.stop()
# stop A stop!
b.stop()
# stop A stop!
c.stop()
# stop A stop!
# stop C stop!
d.stop()
# stop A stop!
# stop C stop!
# stop D stop!
e.stop()
# stop A stop!
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 45/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
a.pause()
b.pause()
c.pause()
d.pause()
# wait D wait!
e.pause()
Why do we care?
Because OO programming is really, really important. Really. Answering this question shows your
understanding of inheritance and the use of Python’s super function. Most of the time the order of
resolution doesn’t matter. Sometimes it does, it depends on your application.
Q141).
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 46/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
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)
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
print(oNode)
oRoot = Node(“root”)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 47/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
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.append(oChild5)
oChild2.append(oChild6)
oChild4.append(oChild7)
oChild3.append(oChild8)
oChild3.append(oChild9)
oChild6.append(oChild10)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 48/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
oRoot.print_all_1()
oRoot.print_all_2()
Ans141:
oRoot.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’>
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 49/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
<Node ‘child9’>
<Node ‘child7’>
<Node ‘child10’>
Why do we care?
Because composition and object construction is what objects are all about. Objects are composed of
stu and they need to be initialised somehow. This also ties up some stu about recursion and use of
generators.
Generators are great. You could have achieved similar functionality to print_all_2 by just constructing a
big long list and then printing it’s contents. One of the nice things about generators is that they don’t
need to take up much space in memory.
It is also worth pointing out that print_all_1 traverses the tree in a depth- rst manner,
while print_all_2 is width- rst. Make sure you understand those terms. Sometimes one kind of traversal
is more appropriate than the other. But that depends very much on your application.
Ans142: A 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 else
occasionally 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 o1and o2 such that 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 rst.
Q143).
Place the following functions below in order of their e ciency. 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
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 50/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
def f1(lIn):
l1 = sorted(lIn)
l2 = [i for i in l1 if i<0.5]
def f2(lIn):
l2 = sorted(l1)
def f3(lIn):
l2 = sorted(l1)
Ans143:
Most to least e cient: f2, f1, f3. To prove that this is the case, you would want to pro le your code.
Python has a lovely pro ling package that should do the trick.
import cPro le
cPro le.run(‘f1(lIn)’)
cPro le.run(‘f2(lIn)’)
cPro le.run(‘f3(lIn)’)
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 51/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 52/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Why Care?
Locating and avoiding bottlenecks is often pretty worthwhile. A lot of coding for e ciency comes
down to common sense – in the example above it’s obviously quicker to sort a list if it’s a smaller list, so
if you have the choice of ltering before a sort it’s often a good idea. The less obvious stu can still be
located through use of the proper tools. It’s good to know about these tools.
Ans144: PYTHONPATH – It has a role similar to PATH. This variable tells the Python interpreter where to
locate the module les imported into a program. It should include the Python source library directory
and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python
installer.
Ans145: PYTHONSTARTUP – It contains the path of an initialization le containing Python source code.
It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains
commands that load utilities or modify PYTHONPATH.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 53/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Ans148: Python is a general-purpose programming language typically used for web development. …
SQLite is one free lightweight database commonly used by Python programmers to store data. Many
highly tra cked websites, such as YouTube, are created using Python.
Ans149: An interpreter is a program that reads and executes code. This includes source code, pre-
compiled code, and scripts. Common interpreters include Perl, Python, and Ruby interpreters, which
execute Perl, Python, and Ruby code respectively.
Ans150: When he began implementing Python, Guido van Rossum was also reading the published
scripts from “Monty Python‘s Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought
he needed a name that was short, unique, and slightly mysterious, so he decided to call the
language Python.
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 54/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
Summary
Reviewer Meghana
Reviewed Item Excellent!! Collection of Python Interview Questions and Answers! Thank
you For sharing!!
Author Rating
Share
R E CO M M E N D E D P O S T S
CATEGORIES
Digital Marketing
SOCIAL
TAGS
angularjs angularjs interview questions automation testing with python aws aws interview questions
Digital Marketing Interview questions django interview questions ext js ext js interview questions
hadoop hadoop interview questions interview questions for Excel VBA interview questions for maongodb
ios interview questions and answers magento interview questions mongo db interview questions node js
node js interview questions oracle scm oracle scm interview questions pentaho bi
ruby cucumber interview questions ruby on rail ruby on rail interview questions
swift programming swift programming interview questions tableau tableau interview questions
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 57/58
10/29/2017 Top 150 Python Interview Questions and Answers | myTectra.com
TCL Interview Questions and Answers-2017 testing with python Typo3 cms Typo3 cms interview questions
web design web design interview questions zend framework zend framework interview questions
10P, IWWA Building, 2nd Floor,7th Main Road, BTM Layout 2nd Stage,Bangalore-
560076,Karnataka, India
[email protected]
[email protected]
+91 9019191856
+1 (209) 222-4733 (USA)
ABOUT US
myTectra a global learning solutions company helps transform people and organization to gain real,
lasting bene ts.Join Today.Ready to Unlock your Learning Potential !
Terms and Conditions
Privacy and Policy
NEWSLETTER SIGNUP
Get an email of every new post! We will never share your address.
Example: [email protected]
https://www.mytectra.com/interview-question/python-real-time-interview-questions-and-answers/ 58/58