Top 50 Python Interview Question and Answers Powered by ©
Top 50 Python Interview Question and Answers Powered by ©
com
Top 50 Python
Interview
Questions & Answers
By
Python-FAQ.COM
In a statically typed language, the type of variables must be known (and usually
declared) at the point at which it is used. Attempting to use it will be an error. In
a dynamically typed language, objects still have a type, but it is determined at
runtime. You are free to bind names (variables) to different objects with a
different type. So long as you only perform operations valid for the type the
interpreter doesn't care what type they actually are.
5) Create a unicode string in python with the string “This is a test string”?
Ans.some_variable = u'This is a test string'
Above example creates a function called my_func that returns the square of the
argument passed.
8) What are the rules for local and global variables in Python?
Ans.If a variable is defined outside function then it is implicitly global.If variable is
assigned new value inside the function means it is local.If we want to make it
global we need to explicitly define it as global. Variable referenced inside the
function are implicit global.
Ans.Output: []
The above code will output [], and will not result in an IndexError.
As one would expect, attempting to access a member of a list using an
index that exceeds the number of members results in an IndexError.
11) What does this list comprehension do:
[x**2 for x in range(10) if x%2==0]
Ans.Sets and dictionaries support it. However tuples are immutable and
have generators but not comprehensions.
Set Comprehension:
r = {x for x in range(2,101)
if not any(x%y==0 for y in range(2,x))}
Dictionary Comprehension:
{i:j for i,j in {1:'a',2:'b'}.items()}
List Boolean
String
Tuple
Normal functions return a single value using return, just like in Java. In Python,
however, there is an alternative, called yield. Using yield anywhere in a function
makes it a generator.
The other is to treat results one at a time, avoiding building huge lists of results
that you would process separated anyway.
17) When should you use generator expressions vs. list comprehensions
in Python and vice-versa?
Ans.Iterating over the generator expression or the list comprehension will do the
same thing. However, the list comp will create the entire list in memory first while
the generator expression will create the items on the fly, so you are able to use it
for very large (and also infinite!) sequences.
Example:
a=[1,2,3]
print a[-1]
print a[-2]
Outputs:
3
2
23) What is the difference between lists and tuples explain with its usage?
Ans. First list are mutable while tuples are not, and second tuples can be hashed
e.g. to be used as keys for dictionaries. As an example of their usage, tuples are
used when the order of the elements in the sequence matters e.g. a geographic
coordinates, "list" of points in a path or route, or set of actions that should be
executed in specific order. Don't forget that you can use them a dictionary keys. For
everything else use lists
a=0
b=0
c=0
module1.py:
import config
config.a =1
config.b =2
config.c=3
print "value of a is %d, value of b is %d, value of c is %d" % (config.a, config
.b, config.c)
------------------------------------------------------------------------
output of module1.py will be “value of a is 1, value
of b is 2, value of c is 3”
30) How do I get a list of all files (and directories) in a given directory in
Python?
Ans.Following is one possible solution there can be other similar ones:-
import os
for dirname,dirnames,filenames in os.walk('.'):
# print path to all subdirectories first
for subdirname in dirnames:
print os.path.join(dirname,subdirname)
# print path to all for filenames.
for filename in filenames:
print os.path.join(dirname,filename)
# Advanced usage:
# editing the 'dirnames' list will stop os.walk()
# from recursing into there.
if '.git'in dirnames:
# don't go into any .git directories.
dirnames.remove('.git')
35) What is GIL? What does it do?Talk to me about the GIL. How does it
impact concurrency in Python? What kinds of applications does it impact
more than others?
37) How do you iterate over a list and pull element indices at the same time?
Ans.You are looking for the enumerate function. It takes each element in a
sequence (like a list) and sticks it's location right before it. For example:
>>>my_list = ['a','b','c']
>>>list(enumerate(my_list))
>>>[(0,'a'),(1,'b'),(2,'c')]
Note that enumerate() returns an object to be iterated over, so wrapping it in
list() just helps us see what enumerate() produces.
my_list =['a','b','c']
for i,char in enumerate(my_list):
print i,char
The output is:
0a
1b
2c
A bad solution would be to iterate over the list and checking for copies
somehow and then remove them.
A very good solution would be to use the set type. In a Python set, duplicates
are not allowed.
46) Print the length of each line in the file ‘file.txt’ not including any
whitespaces at the end of the lines?
Ans. With open("filename.txt","r") as f1:
print len(f1.readline().rstrip())
rstrip() is an inbuilt function which strips the string from the right end of spaces or
tabs (whitespace characters).