0% found this document useful (0 votes)
388 views12 pages

Top 50 Python Interview Question and Answers Powered by ©

Uploaded by

Khadija Lasri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
388 views12 pages

Top 50 Python Interview Question and Answers Powered by ©

Uploaded by

Khadija Lasri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Top 50 Python Interview Question and Answers powered by © www.python-faq.

com

Top 50 Python
Interview
Questions & Answers
By
Python-FAQ.COM

Python Preparation Guide powered by www.python-faq.com Page 1


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

1) What type of a language is python? Interpreted or Compiled?


Ans- Python is an interpreted, interactive, object-oriented programming

2) What is python’s standard way of identifying a block of code?


Ans.Indentation.

3) Is python statically typed or dynamically typed?


Ans.Dynamic.

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.

4) Is python strongly typed or weakly typed language?


Ans.Strong.

In a weakly typed language a compiler / interpreter will sometimes change the


type of a variable. For example, in some languages (like JavaScript) you can add
strings to numbers 'x' + 3 becomes 'x3'. This can be a problem because if you
have made a mistake in your program, instead of raising an exception execution
will continue but your variables now have wrong and unexpected values. In a
strongly typed language (like Python) you can't perform operations inappropriate
to the type of the object - attempting to add numbers to strings will fail. Problems
like these are easier to diagnose because the exception is raised at the point
where the error occurs rather than at some other, potentially far removed, place.

5) Create a unicode string in python with the string “This is a test string”?
Ans.some_variable = u'This is a test string'

6) What is the python syntax for switch case statements?


Ans.Python doesn’t support switch­case statements. You can use if-else
statements for this purpose.

7) What is a lambda statement? Provide an example.


Ans.A lambda statement is used to create new function objects and then return
them at runtime.

Example: my_func = lambda x:x**2

Python Preparation Guide powered by www.python-faq.com Page 2


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

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.

9) What is the purpose of #!/usr/bin/python on the first line in the above


code? Is there any advantage?

Ans. By specifying #!/usr/bin/python you specify exactly which interpreter will


be used to run the script on a particular system.This is the hardcoded path to
the python interpreter for that particular system. The advantage of this line is that
you can use a specific python version to run your code.

10) What is the output of the following program?


list =['a','b','c','d','e']
print list[10:]

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.Creates the following list:[0,4,16,36,64]

12) Do sets, dictionaries and tuples also support comprehensions?

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()}

Since, {1:'a',2:'b'}.items() returns a list of 2-Tuple.


i is the first element of tuple j is the second.

Python Preparation Guide powered by www.python-faq.com Page 3


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

13) What are some mutable and immutable data-types/data-structures in


python?
Ans.

Mutable Types Immutable Types


Dictionary Number

List Boolean

String

Tuple

14) What are generators in Python?


Ans.A generator is simply a function which returns an object on which you can
call next, such that for every call it returns some value, until it raises a Stop
Iteration exception, signaling that all values have been generated. Such an
object is called an iterator.

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.

15) What can you use Python generator functions for?


Ans.One of the reasons to use generator is to make the solution clearer for
some kind of solutions.

The other is to treat results one at a time, avoiding building huge lists of results
that you would process separated anyway.

16) When is not a good time to use python generators?


Ans.Use list instead of generator when:
1- You need to access the data multiple times (i.e. cache the results instead of
recomputing them)
2- You need random access (or any access other than forward sequential order):
3- You need to join strings (which requires two passes over the data)
4- You are using PyPy which sometimes can't optimize generator code as much
as it can with normal function calls and list manipulations.

Python Preparation Guide powered by www.python-faq.com Page 4


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

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.

18) What is a negative index in Python?


Ans.Python arrays and list items can be accessed with positive or negative
numbers. A negative Index accesses the elements from the end of the list
counting backwards.

Example:
a=[1,2,3]

print a[-1]
print a[-2]

Outputs:
3
2

19) What is the difference between range and xrange functions?


Ans.Range returns a list while xrange returns an xrange object which take the
same memory no matter of the range size. In the first case you have all items
already generated (this can take a lot of time and memory). In Python 3
however, range is implemented with xrange and you have to explicitly call the
list function if you want to convert it to a list.

20) What is PEP8?


Ans. PEP8 is a coding convention (a set of recommendations) how to write your
Python code in order to make it more readable and useful for those after you.

21) How can I find methods or attributes of an object in Python?


Ans. Built-in dir() function of Python ,on an instance shows the instance variables
as well as the methods and class attributes defined by the instance's class and
all its base classes alphabetically. So by any object as argument to dir() we can
find all the methods & attributes of the object’s class

Python Preparation Guide powered by www.python-faq.com Page 5


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

22) What is the statement that can be used in Python if a statement is


required syntactically but the program requires no action?
Ans. pass

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

24) What is the usage of “self” in python?


Ans. “Self” is a variable that represents the instance of the object to itself. In
most of the object oriented programming languages, this is passed to the
methods as a hidden parameter that is defined by an object. But, in python it is
passed explicitly. It refers to separate instance of the variable for individual
objects. The variables are referred as “self.xxx”.

25) How is memory managed in Python?


Ans. Memory management in Python involves a private heap containing all
Python objects and data structures. Interpreter takes care of Python heap and
the programmer has no access to it. The allocation of heap space for Python
objects is done by Python memory manager. The core API of Python provides
some tools for the programmer to code reliable and more robust program. Python
also has a built-in garbage collector which recycles all the unused memory.

The gc module defines functions to enable /disable garbage collector:


gc.enable() -Enables automatic garbage collection. gc.disable
()-Disables automatic garbage collection

26) What is __init__.py?


Ans.It is used to import a module in a directory, which is called
package import.

Python Preparation Guide powered by www.python-faq.com Page 6


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

27) Print contents of a file ensuring proper error handling?


Ans.
try:
with open('filename','r')as f:
print f.read()
except IOError:
print "No such file exists"

28) How do we share global variables across modules in Python?


Ans. We can create a config file and store the entire global variable to be
shared across modules in it. By simply importing config, the entire global
variable defined will be available for use in other modules.

For example I want a, b & c to share between modules. config.py :

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”

29) Does Python support Multithreading?


Ans.Yes

Python Preparation Guide powered by www.python-faq.com Page 7


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

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')

31) How to append to a string in Python?


Ans.The easiest way is to use the += operator. If the string is a list of
character, join() function can also be used.

32) How to convert a string to lowercase in Python?


Ans.use lower() function.
Example:
s ='MYSTRING' prints.lower()

33) How to convert a string to lowercase in Python?


Ans.Similar to the above question. use upper() function instead.

34) How to check if string A is substring of string B?


Ans. The easiest way is to use the in operator.
>> ‘abc’ in ‘abcdefg’: True

Python Preparation Guide powered by www.python-faq.com Page 8


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

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?

Ans.Python's GIL is intended to serialize access to interpreter internals from


different threads. On multi-core systems, it means that multiple threads can't
effectively make use of multiple cores. (If the GIL didn't lead to this problem,
most people wouldn't care about the GIL - it's only being raised as an issue
because of the increasing prevalence of multi-core systems.)
Note that Python's GIL is only really an issue for CPython, the reference
implementation. Jython and IronPython don't have a GIL. As a Python
developer, you don't generally come across the GIL unless you're writing a C
extension. C extension writers need to release the GIL when their extensions do
blocking I/O, so that other threads in the Python process get a chance to run.

36) Print the index of a specific item in a list?


Ans.use the index() function
>>>["foo","bar","baz"].index('bar')
1

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.

An example that directly answers the question is given below

my_list =['a','b','c']
for i,char in enumerate(my_list):
print i,char
The output is:

0a
1b
2c

Python Preparation Guide powered by www.python-faq.com Page 9


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

38) How does Python's list.sort work at a high level? Is it stable?


What's the runtime?
Ans.In early python-versions, the sort function implemented a modified
version of quicksort. However, it was deemed unstable and as of 2.3 they
switched to using an adaptive mergesort algorithm.

39) How can we pass optional or keyword parameters from one


function to another in Python?
Ans. Gather the arguments using the * and ** specifiers in the function's
parameter list. This gives us positional arguments as a tuple and the keyword
arguments as a dictionary. Then we can pass these arguments while calling
another function by using * and **:
>>> def fun1(a,*tup,**keywordArg):
keywordArg['width']='23.3c'
fun2(a, *tup,**keywordArg)

40) Explain the role of repr function.


Ans. Python can convert any value to a string by making use of two functions
repr() or str(). The str() function returns representations of values which are
human-readable, while repr() generates representations which can be read by
the interpreter.

repr() returns a machine-readable representation of values, suitable for


an exec command.

41) Python - How do you make a higher order function in Python?


Ans. A higher-order function accepts one or more functions as input and returns
a new function. Sometimes it is required to use function as data To make high
order function , we need to import functools module The functools.partial()
function is used often for high order function.

42) What is map?


Ans. The syntax of map is: map(aFunction,aSequence)
The first argument is a function to be executed for 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.

Python Preparation Guide powered by www.python-faq.com Page 10


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

43) Why is not all memory freed when python exits?


Ans. Objects referenced from the global namespaces of Python modules are not
always de-allocated when Python exits. This may happen if there are circular
references. There are also certain bits of memory that are allocated by the C
library that are impossible to free (e.g. a tool like the one Purify will complain
about these). Python is, however, aggressive about cleaning up memory on exit
and does try to destroy every single object. If you want to force Python to delete
certain things on de-allocation, you can use the at exit module to register one or
more exit functions to handle those deletions.

44) What is a docstring?


Ans. docstring is the documentation string for a function. It can be accessed by
>> function_name.__doc__

45) Given the list below remove the repetition of an element.


Ans. words =['one','one','two','three','three','two']

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.

So, list(set(words)) would remove the duplicates.

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).

47) What are Python decorators?


Ans. A Python decorator is a specific change that we make in Python syntax to
alter functions easily.

Python Preparation Guide powered by www.python-faq.com Page 11


Top 50 Python Interview Question and Answers powered by © www.python-faq.com

48) What is namespace in Python?


Ans. In Python, every name introduced has a place where it lives and can be
hooked for. This is known as namespace. It is like a box where a variable
name is mapped to the object placed. Whenever the variable is searched out,
this box will be searched, to get corresponding object.

49) Explain how to copy an object in Python.?


Ans. There are two ways in which objects can be copied in python. Shallow
copy & Deep copy. Shallow copies duplicate as minute as possible whereas
Deep copies duplicate everything.

If a is object to be copied then …


-copy.copy(a) returns a shallow copy of a.
-copy.deepcopy(a) returns a deep copy of a.

50) What is Pickling and unpickling?


Ans. Pickle is a standard module which serializes & de-serializes a python
object structure. pickle module accepts any python object converts it into a
string representation & dumps it into a file(by using dump() function) which can
be used later, process is called pickling. Whereas unpickling is process of
retrieving original python object from the stored string representation for use.

Python Preparation Guide powered by www.python-faq.com Page 12

You might also like