Monday, May 11, 2009

Python Interview Questions and Answers



Hi Everybody,

As always interview questions but this time I was lucky to be interviewed for Python, which I had recent experience on. And the interviewer was great. He told me that he had pretty much fundamental and short questions to ask and he joked about MS interviewees will be joyed with this kind of interview process.

This was basically a python position but this made me feel why people cannot do with other programming language experts for python because a python programmer is really way too different than a C++ or Java programmer. Since I am a C++ programmer with recent experience in Python, I was considered for the position. It was fun going through the interview since it was web conference coding interview.

What I had gone through was the LinuxCBT edition of python which helped me a lot. If I had not referred that I would have done miserably.

I had tried searching for python questions over the internet but was not too lucky since I got only a few of them which made sense. Some of them were asked but restricting to just a couple of them. So I think my questions and answers will really help people to get a good idea on what can be asked for python interviews and also for people who are getting interviewed on python. I really appreciate comments and improvements on the questions and answers.

Hope the information helps.....


1. Name five modules that are included in python by default

2. Name a module that is not included in python by default

3. What is __init__.py used for?

4. When is pass used for?

5. What is a docstring?

6. What is list comprehension?

7. What is map?

8. What is the difference between a tuple and a list?


Ans. This is the most frequently asked question on python.

A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.

Other significant difference is of the syntax. A list is defined as

list1 = [1,2,5,8,5,3,]
list2 = ["Sachin", "Ramesh", "Tendulkar"]

A tuple is defined in the following way

tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")

So the difference is in the type of brackets.


Coding questions

9. Using various python modules convert the list a to generate the output 'one, two, three'

a = ['one', 'two', 'three']

ANSWER:




>>> a = ['one','two','three']
>>> ','.join(a)
'one,two,three'

10. What would the following code yield?

word = 'abcdefghij'
print word[:3] + word[3:]

Ans. This will print the word 'abcdefghij'

11. Optimize these statements as a python programmer

word = 'word'
print word.__len__()


ANSWER:
>>> print 'word'.__len__()
4


12. Write a program to print all the contents of a file


Ans.

try:
  f1=open("filename.txt","r")
except Exception, e:
  print "%s" %e  

print f1.readlines() 
 
ANSWER2:
with open("tmp1.txt", "r") as f:
     f.readlines() 

13. What will be the output of the following code

a = 1
a,b=a+1,a+1
print a
print b

Ans.

2
2

Here in the second line a,b=a+1,a+1 means that a=a+1 and b=a+1 which is 2. But this is the python way of initialization which a python programmer should understand.

14. Given the list below remove the repetition of an element. All the elements should be uniquewords = ['one', 'one', 'two', 'three', 'three', 'two']

ANSWER:

>>> set(uniquewords)
set(['three', 'two', 'one'])

15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example

{'one':2,'two':2,'three':2}

ANSWER:

>>> l = ['one', 'one', 'two', 'three', 'three', 'two', 'one', 'one', 'two']
>>> d = {}
>>> for w in l:
...   d[w] = 1 + d.get(w,0)
...
>>> d
{'three': 2, 'two': 3, 'one': 4}

16.Write the following logic in Python:
If a list of words is empty, then let the user know it's empty, otherwise let the user know it's not empty.


Ans.
a=[]
if len(a):
print"The list is not empty"
else:

print"The list is empty"


17. Demonstrate the use of exception handling in python.
Ans.

a=[1,2,3,4]
try:
print a[5]
except Exception, e # This was important. Just do not say except: and print out something. It is
print e # Important to know what is the error

>>> a=[1,2,3,4]
>>> try:
...   print a[5]
... except Exception, e:
...   print "Error %s" % e
...
Error list index out of range

18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines.
Ans.
>>> f1 = open("abc.py", 'r')
>>> i=0
>>> for line in iter(f1):
...   print "Length of line %d is %d" % (i, len(line.rstrip()))
...   i+=1
...
Length of line 0 is 11
Length of line 1 is 21


19. Print the sum of digits of numbers starting from 1 to 100

Ans. print sum(range(1,101))

This is way too easy but just who know python. Since I am a C++ Programmer, I started writing a for loop to add up which was way too dumb. Hope you don't make this mistake.

Python is known for it short syntax and easy to use functions.

20. 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']

Ans.




>>>num_strings = ['1','21','53','84','50','66','7','38','9']
>>>[int(j) for j in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]

21. Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]

Ans.
>>>num_strings = [1,21,53,84,50,66,7,38,9]
>>>o, e = [], []
>>>[o.append(n) if n % 2 else e.append(n) for n in num_strings]
[None, None, None, None, None, None, None, None, None]
>>>o,e
([1, 21, 53, 7, 9], [84, 50, 66, 38])

>>> num_strings = [1,21,53,84,50,66,7,38,9]
>>> odd, even = filter(lambda x:x%2, num_strings), filter(lambda x: not x%2, num_strings)
>>> print odd,even
[1, 21, 53, 7, 9] [84, 50, 66, 38]


22. Write a program to sort the following intergers in list
nums = [1,5,2,10,3,45,23,1,4,7,9]

nums.sort() # This is the quickest sorting algorithm. This is the best possible way to sort.
print nums

23. Write a for loop that prints all elements of a list and their position in the list.
abc = [4,7,3,2,5,9] 
Ans. 
 
>>>abc = [4,7,3,2,5,9]
>>>for i, v in enumerate(abc):
...   print i,v
... 
0 4
1 7
2 3
3 2
4 5
5 9

24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug.
n = [1,2,5,10,3,100,9,24]

for e in n:
if e<5: 
    n.remove(e)
print n

Ans. The output here will be

[2,3,5,10,100,9,24] which means the 1st and the 5th elements are removed.

It should be implemented as below.

>>> n = [1,2,5,10,3,100,9,24]
>>> nlist = filter(lambda x: x >= 5, n)
>>> print nlist
[5, 10, 100, 9, 24]


list.remove(element) will remove the element, and shrink the list. If
you are iterating over the same list at that time, and you wanted to
go to next element, the next element may very well be the one after.
Here is what is happening in the problem: The 0th element in the list
is less than 5 and is removed, thus, making the list shorter by one
element. The next iteration in the for loop goes to n[1], but n[0]
now is 2, so the loop skips element 2 and doesn't remove it. Same
thing happens at 100, but it is ok to skip 100 as it is > 5

25. What will be the output of the following
def func(x,*y,**z):
print z

func(1,2,3)

Ans.

Here the output is :

{}

If I print all the variables, namely x, y and z it yeilds me this

1 (2,3) {}

* and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments (like your sum function that took range of numbers from 0
.. 100. Pretty cool, eh?


26. Write a program to swap two numbers.
a = 5
b = 9

def swap(c,d):
return d,c

swap(a,b)

This will print the swapped values of a and b

(9,5)

OR if this does not seem convincing,
a, b = 5, 10

t = a
a=b
b=t

print a,b

>>> a = 5
>>> b = 10
>>> a,b=b,a
>>> a
10
>>> b
5

27. What will be the output of the following code
class C(object):
def__init__(self):
self.x =1

c=C()
print c.x
print c.x
print c.x
print c.x

Ans.

All the outputs will be 1

1
1
1
1

28. What is wrong with the code
func([1,2,3]) # explicitly passing in a list
func()             # using a default empty list

def func(n = []):
#do something with n

print n

Ans. I tried running the code with my addition of printing the value of n in the function and found out the following result

func([1,2,3]) resulted in [1,2,3]
while func() resulted in []

29. What all options will work?
a.

n = 1
print n++

b.

n = 1
print ++n

c.

n = 1
print n+=1

d.

int n = 1
print n = n+1

e.

n =1
n = n+1

From the above options I believe the following will work

b. and e.

There are some problems with a, c and d.

if you try running the code in a , it does not accept n++ but it accepts ++n

n+=1 is not accepted while in d the variable is preceded by an int which is not pythonically correct.

30. In Python function parameters are passed by value or by reference?
Ans. Please refer to this


31.Remove the whitespaces from the string.
s = 'aaa bbb ccc ddd eee'

Ans.

a = string.split(s)
print a
['aaa', 'bbb', 'ccc', 'ddd', 'eee'] # This is the output of print a

print string.join(a)
aaa bbb ccc ddd eee # This is the output of print string.join(a)

32. What does the below mean?
s = a + '[' + b + ':' + c + ']'

33. Optimize the below code

def append_s(words):
new_words=[]
for word in words:
new_words.append(word + 's')
return new_words

for word in append_s(['a','b','c']):
print word

The above code adds a trailing s after each element of the list. Is there a better way one can write the above script?

34. If given the first and last names of bunch of employees how would you store it and what datatype?

Ans. Either a dictionary or just a list with first and last names included in an element.


35.
36.

















30 comments:

bluehive said...

Hi,

Thanks for posting these questions. Very helpful.

Thanks,
Blue

TIPS - Tricks Blackberry said...

Hi

I read this post two times.

I like it so much, please try to keep posting.

Let me introduce other material that may be good for our community.

Source: Free interview questions

Best regards
Henry

nandu said...

Thank you so much for putting these questions up they have been most helpful. :-)

The answer to question 16 given by the interviewer in incorrect because instead of putting print"The list is not empty" in the if block he/she has put it in the else block. The correct code should be:

a = []
if len(a):
print "the list is not empty"
else:
print "the list is empty"

this works because if the list is empty if len(a): evaluates to false.

in Python empty lists evaluate to (false) and if it is not empty it will evaluate to true. Hope that helps.

Thanks once again for this service.

Rahul Grandhi said...

For Question 24:

you cannot remove from the same list as the list truncates and the remaining variables get assigned new indices every time you remove something. So they constantly changing. The only way to do this is to take a temp list and proceed.

temp = []
for num in n:
if(num >= 5):
temp.append(num)

n = temp

gradient descent said...
This comment has been removed by the author.
gradient descent said...

For #24 you can use numpy:

import numpy as np
n = np.array([1,2,5,10,3,100,9,24])
n = n[n >= 5]

David said...

Better yet on #24, use list comprehension:

n = [1,2,5,10,3,100,9,24]
[e for e in n if e>=5]

Milind said...

9. Using various python modules convert the list a to generate the output 'one, two, three'

a = ['one', 'two', 'three']

Ans: ', '.join(a)

12. Write a program to print all the contents of a file

Ans.
with open("tmp1.txt", "r") as f:
f.readlines()

14. Given the list below remove the repetition of an element. All the elements should be unique
words = ['one', 'one', 'two', 'three', 'three', 'two']
Ans: set(words)

15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example

{'one':2,'two':2,'three':2}

Ans.

l = ('one', 'two', 'one', 'three', 'three', 'two')
d = {}
>>> for w in l:
... d[w] = 1 + d.get(w, 0)
...
>>> d
{'three': 2, 'two': 2, 'one': 2}

17. Demonstrate the use of exception handling in python.

try:
s
except NameError, e:
print "Error accessing variable. [%s]" % e
finally:
print "Finally block"

18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines.

Ans:
i = 0
>>> with open("junk.txt", "r") as f:
... for line in iter(f):
... print "Length of line %d is %d" % (i, len(line.rstrip()))
... i += 1
...
1
2
3

20. 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']

Ans.

>>> num_strings = ['1','21','53','84','50','66','7','38','9']
>>> [int(j) for j in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]

21. Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]

>>> num_strings = [1,21,53,84,50,66,7,38,9]
>>>
>>> o, e = [], []
>>> [o.append(n) if n % 2 else e.append(n) for n in num_strings]
[None, None, None, None, None, None, None, None, None]
>>> o
[1, 21, 53, 7, 9]
>>> e
[84, 50, 66, 38]
>>>

23. Write a for loop that prints all elements of a list and their position in the list.


>>> for i, v in enumerate(num_strings):
... print i, v
...
0 1
1 21
2 53
3 84
4 50
5 66
6 7
7 38
8 9

24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug.

list.remove(element) will remove the element, and shrink the list. If
you are iterating over the same list at that time, and you wanted to
go to next element, the next element may very well be the one after.
Here is what is happening in the problem: The 0th element in the list
is less than 5 and is removed, thus, making the list shorter by one
element. The next iteration in the for loop goes to n[1], but n[0]
now is 2, so the loop skips element 2 and doesn't remove it. Same
thing happens at 100, but it is ok to skip 100 as it is > 5

25. * and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments (like your sum function that took range of numbers from 0
.. 100. Pretty cool, eh?

griesrt said...

25. one-liner
>>> new_strings = [1, 2, 3, 4, 5, 6, 7, 10, 69, 21]
>>> print(filter(lambda x: x > 5, new_strings))
[6, 7, 10, 69, 21]

Filtering new_strings list with the lambda expression "if x more than 5". If it is then I return.

19.
range(1, 100) isn't inclusive of the second parameter passed in. I'm not sure if you wanted to add 100 into that sum. Also, xrange() is better to use than range because it is a generator so it uses elements dynamically. 'Range' creates a list so it would take up lots of memory for a long list.

30. In Python, values are always passed by reference. By that I mean that you pass the value into the function but then python acts upon the variable as a reference. This is because everything is an object in python and all names to variables are pointing to a reference to a variable stored in memory.

I hope you got the job!

Robert G.

rups said...

26. Write a program to swap two numbers.

a=5
b=9
a,b = b,a
print a
9
print b
5
its so simple........

SSDP said...

Q31: remove the whitespaces
>>> s = 'aaa bbb ccc ddd eee'
>>> s = s.replace(' ', '')
'aaabbbcccdddeee'
better use RegEx

Q33: optimize the append_s(words) function:

use map & lambda functions:
Ex:
>>> nstr = ['1', '21', '53', '44', '36', '94']
>>> map(lambda x: x + 's', nstr)
['1s', '21s', '53s', '44s', '36s', '94s']

Sasi said...
This comment has been removed by the author.
Day Dreamer said...
This comment has been removed by the author.
Day Dreamer said...

Note:- in answers in i m using "____"
as white spaces are not allowed in comments.Python is particular about indentation.

=====================================


Ans 1. cStringIO, code, copy_reg, datetime, encodings
-------------------------------------
smart way to get the ans 1 is.

import sys
sys.modules

where sys.modules return a dictionary with all the sourced modules

===================================

Ans 8 :- "A tuple is a list"
Its Wrong. Tuple, List And Strings Are Sequences.

===================================

Ans 9:- a = ['one', 'two', 'three']
print (','.join(a))

===================================

Ans 11:- print 'word'.__len__()

===================================

Ans 14:-
words = ['one', 'one', 'two', 'three', 'three', 'two']
words = list(set(words))

===================================

Ans 15:-
allNum = [1,2,3,2,1,5,14,3,14,5,6,7,5]
dictNum = {}
for num in allNum:
____if not num in dictNum:
________dictNum[num] = 1
________continue
____dictNum[num] += 1
print dictNum

===================================

Ans 16:-
a = [] ## something

if not a:
____print 'The list is not empty'
## To Avoid Else
## if u r in loop use continue
## I assume it in a function
## So ,
____return(0)
print 'The list is not empty'

===================================

Day Dreamer said...

=====================================

Ans 20:-

num_strings = ['1','21','53','84','50','66','7','38','9']
for i in range(len(num_strings)):
____num_strings[i] = int(i)
print num_strings

===================================

Ans 21:-

In Place Of Insert User .append, with this you will get rid of ceven and codd(counters).

===================================

Ans 24:-

As You Go Through For Loop, it in the back is operating on the index values, so it operates on the number "1" at index 0, it removes it ans shifts the number "2" ai index 0, for control, it already operated on index 1, so it skips number "2" and march on to next value.

To Confirm Test, In List Insert a new value less than 5 after number "3" , it will skip it too.

===================================

Ans 29:- ONly option e will work

===================================

Ans 33:- List Comprehension

===================================

rjamerson said...

24. For loop creates a list by using range, however every deletion shortens the list and eventually you will request an index out of range for the list. The following fixes that problem:

n = [1,2,5,10,3,100,9,24]
n_len = len(n)
pos = 0
while pos < n_len:
if n[pos] < 5:
n.remove(n[pos])
n_len -= 1
else:
pos += 1

Michael said...

For question 19, your answer leaves out the number 100. range(1,100) gives you [1, 2, ..., 98, 99].

Thus, I think the correct answer is:

print sum(range(1,101))

Ravi said...

25. Ans You could combine built-in function filter() and lambda to achieve the end-result. Code is as follows:

n = [1,2,5,10,3,100,9,24]
nlist = filter(lambda x: x >= 5, n)
print nlist

Nitin GUpta said...
This comment has been removed by the author.
bardia said...

Nice post but it has many problems. som of them are:

Ans 20.
int_list = map(lambda x:int(x), num_strings)

Ans 21.
odd, even = filter(lambda x:x%2, int_list), filter(lambda x: not x%2, int_list)

Ans 24.
Using filter is better.

Ans 26.
a, b = b, a

Ans 31.
s = 'aaa bbb ccc ddd eee'
result = s.replace(' ','')

Ans 33.
use list comprehension.
new_words = [itm+'s' for itm in words]

urs good friend said...

Hi,friends im going to attend an interview in 10days i have put python along with C,C++

what are the main concepts should focus on python in the interview point of view?

thank you all

Сергей Мисюк said...

Q28:

The problem is that default value will be evaluated only once. If this function modifies n then n can be non-empty next time you call it with no arguments.

RSK said...

thanks ,this blog is very helpful for new python users !


python!

Sonal Dubey said...

Thanks a lot!! its really a nice post and after doing these questions i feel confident about giving a python interview

._/<>/\/ 4774/\/ said...

Question 19 asks us to sum the digits, not the numbers themselves.

Not sure if this is just a typo on your part, but to do exactly what was asked I would do the following:
>> numberRange = range(1,101)
>> def sumDigits(n):
>> ... return n if n < 10 else n % 10 + sumDigits(n // 10)
>> sum(map(sumDigits, numberRange))
resulting in 901.

For the question you answered you can use a more efficient method. Add the largest to the smallest number, note this is equal to the sum of the second largest and second smallest, and so on. So take this number and multiply by the number of such pairs (if a middle number exists it is half of this pair sum, so that still works). The largest number is equal to the range's length so:
>> numberRange = range(1,101)
>> length = len(numberRange)
>> (length + 1) * length // 2
resulting in 5050 as expected.

If the range was integers starting at an arbitrary number you can use this same method, but more explicitly, like so:
>> (numberRange[0] + numberRange[-1]) * len(numberRange) // 2
For example for range(98,101) this would result in 297 (i.e. 98+99+100) or for range(-2,101) it would result in 5047 (i.e. 5050-1-2). and of course it still works for range(1,101).

Manmet Kaur said...

Great post!
Python Interview Questions - http://www.hub4tech.com/interview/python
Python Online Quiz- http://www.hub4tech.com/Python-online-quiz-tes
Online Training Python- http://www.hub4tech.com/training/python-online-training.php?id=71
Machine Learning Tutorial-http://www.hub4tech.com/machine-learning-tutorial

Interview questions answers pdf said...

Python Interview Questions and Answers
http://allinterviewquestionsandanswerspdf.blogspot.in/2016/06/top-25-python-interview-questions-and.html

bharath venkat said...

Visit More

Priya Kannan said...

Somebody necessarily help to make severely posts I might state. This is the first time I frequented your website page and to this point? I surprised with the research you made to create this particular post extraordinary. Well done admin..
Python Training in Chennai

nutana meka said...

This is an excellent information thank you for sharing this
python online training
interview questions...