Top Python Interview Questions and Answers
Top Python Interview Questions and Answers
Go through these Python interview questions and land your dream job in Data Science, Machine
Learning or just Python coding. Here we have compiled the questions on the topics like Lists Vs.
Tuples, inheritance example, multithreading, important Python modules, difference between NumPy
& SciPy, TKinter GUI, Python as a OOP & functional programming language, Flask database
connection and some important sample codes. Learn Python from Intellipaat Python training and
excel in your career.
2. What is Python?
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 has fewer syntactical constructions than other languages.
PYTHONPATH − It has a role similar to PATH. This variable tells the Python interpreter where to
locate the module files 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
PYTHONSTARTUP − It contains the path of an initialization file 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
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in
an import statement. Set this variable to any value to activate it.
String
List
Tuple
Dictionary
LIST TUPLES
Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples. Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20)
GET CERTIFIED
1. Python memory is managed by Python private heap space. All Python objects and data
structures are located in a private heap. The programmer does not have an access to this
private heap and interpreter takes care of this Python private heap.
2. The allocation of Python heap space for Python objects is done by Python memory manager.
The core API gives access to some tools for the programmer to code.
3. Python also have an inbuilt garbage collector, which recycle all the unused memory and
frees the memory and makes it available to the heap space.
Inheritance allows One class to gain all the members(say attributes and methods) of another class.
Inheritance provides code reusability, makes it easier to create and maintain an application. The
class from which we are inheriting is called super-class and the class that is inherited is called a
derived / child class.
1. Single Inheritance – where a derived class acquires the members of a single super class.
2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is
inherited from base2.
3. Hierarchical inheritance – from one base class you can inherit any number of child classes
4. Multiple inheritance – a derived class is inherited from more than one base class.
1. Whenever Python exits, especially those Python modules which are having circular
references to other objects or the objects that are referenced from the global namespaces
are not always de-allocated or freed.
2. It is impossible to de-allocate those portions of memory that are reserved by the C library.
3. On exit, because of having its own efficient clean up mechanism, Python would try to de-
allocate/destroy every other object.
The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys
and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed
by keys.
The following example contains some keys. Country, Capital & PM. Their corresponding values are
India, Delhi and Modi respectively.
dict={‘Country’:’India’,’Capital’:’Delhi’,’PM’:’Modi’}
print dict[Country]
11. Write a one-liner that will count the number of capital letters in a file. Your code should work
even if the file is too big to fit in memory.
Let us first write a multiple line solution and then convert it to one liner code.
2 count = 0
3 text = fh.read()
4 for character in text:
5 if character.isupper():
6 count += 1
list.sort()
print (list)
15. What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as negative numbers. The
numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the
process goes on like that.
The index for the negative number starts from ‘-1’ that represents the last index in the sequence and
‘-2’ as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to
except the last character that is given as S[:-1]. The negative index is also used to show the index to
represent the string in correct order.
To modify the strings, Python’s “re” module is providing 3 methods. They are:
sub() – finds all substrings where the regex pattern matches and then replace them with a
different string
subn() – it is similar to sub() and also returns the new string along with the no. of
replacements.
For the most part, xrange and range are the exact same in terms of functionality. They both provide
a way to generate a list of integers for you to use, however you please. The only difference is that
range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates
the values as you need them with a special technique called yielding. This technique is used with a
type of object known as generators. That means that if you have a really gigantic range you’d like to
generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are
working with, as range will use as much memory as it can to create your array of integers, which can
result in a Memory Error and crash your program. It’s a memory hungry beast.
Pickle module accepts any Python object and converts it into a string representation and dumps it
into a file by using dump function, this process is called pickling. While the process of retrieving
original Python objects from the stored string representation is called unpickling.
map function executes the function given as the first 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
We can get the indices of N maximum values in a NumPy array using the below code:
import numpy as np
print(arr.argsort()[-3:][::-1])
A module is a Python script that generally contains import statements, functions, classes and
variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and
DLL files can also be modules.Inside the module, you can refer to the module name as a string that is
stored in the global variable name .
Python provides libraries / modules with functions that enable you to manipulate text files and
binary files on file system. Using them you can create files, update their contents, copy, and delete
files. The libraries are : os, os.path, and shutil.
Here, os and os.path – modules include functions for accessing the filesystem
In python generally “with” statement is used to open a file, process the data present in the file, and
also to close the file without calling a close() method. “with” statement makes the exception
handling simpler by providing cleanup activities.
Python allows you to open files in one of the three modes. They are:
read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”,
“w”, “rw”, “a” respectively.
A text file can be opened in any one of the above said modes by specifying the option “t” along with
“r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.A binary file
can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”,
“rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”.
25. How many kinds of sequences are supported by Python? What are they?
Python supports 7 sequence types. They are str, list, tuple, unicode, byte array, xrange, and buffer.
where xrange is deprecated in python 3.5.X.
Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of
a given string. For instance, we can define a regular expression to match a single character or a digit,
a telephone number, or an email address, etc.The Python’s “re” module provides regular expression
patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for
search text strings, or replacing text strings along with methods for splitting text strings based on the
pattern defined.
4. print(line)
1. In an ideal world, NumPy would contain nothing but the array data type and the most basic
operations: indexing, sorting, reshaping, basic element wise functions, et cetera.
2. All numerical code would reside in SciPy. However, one of NumPy’s important goals is
compatibility, so NumPy tries to retain all features supported by either of its predecessors.
3. Thus NumPy contains some linear algebra functions, even though these more properly
belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra
modules, as well as many other numerical algorithms.
4. If you are doing scientific computing with python, you should probably install both NumPy
and SciPy. Most new features belong in SciPy rather than NumPy.
a) abc = 1,000,000
d) a_b_c = 1,000,000
Answer: b
c) invalid code
Answer: C
31. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ?
25
33. Name few Python modules for Statistical, Numerical and scientific computations ?
numPy – this module provides an array/matrix type, and it is useful for doing computations on
arrays. scipy – this module provides methods for doing numeric integrals, solving differential
equations, etc pylab – is a module for generating and saving plots
TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI tools
or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications.
The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.
Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on
classes and instances of those classes called objects. The features of OOP are:
It means running several different programs at the same time concurrently by invoking multiple
threads. Multiple threads within a process refer the data space with main thread and they can
communicate with each other to share information more easily.Threads are light-weight processes
and have less memory overhead. Threads can be used just for quick task like calculating results and
also running other processes in the background while the main program is running.
Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are
provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what
methods must be implemented by its implementation subclasses. The use of ABC’c provides a sort of
“understanding” about methods and their expected behaviour. This module was made available
from Python 2.7 version onwards.
Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x
is a property of a user-defined class, then the class would have methods called setX() and getX().
Python has an @property “decorator” that allows you to ad getters and setters in order to access
the attribute of the class.
Both append() and extend() methods are the methods of list. These methods a re used to add the
elements at the end of the list.
append(element) – adds the given element at the end of the list which has called this method.
extend(another-list) – adds the elements of another-list at the end of the list which is called the
extend method.
40. Name few methods that are used to implement Functionally Oriented Programming in
Python?
Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are
very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset
of a list.
map() – it is a built-in function that applies the function to each item in an iterable.
reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.
x = [‘ab’, ‘cd’]
print(len(map(list, x)))
A TypeError occurs as map has no len().
x = [‘ab’, ‘cd’]
print(len(list(map(list, x))))
43. Which of the following is not the correct syntax for creating a set?
1. a) set([[1,2],[3,4]])
2. b) set([1,2,2,3,4])
3. c) set((1,2,3,4))
4. d) {1,2,3,4}
Answer : a
Sometimes, when we want to iterate over a list, a few methods come in handy.
1. filter()
[6, 7]
1. map()
1. reduce()
-13
after_request() : They are called after a request and pass the response that will be sent to
the client
teardown_request(): They are called in situation when exception is raised, and response are
not guaranteed. They are called after the response been constructed. They are not allowed
to modify the request, and their values are ignored.
46. Write a Python function that checks whether a passed string is palindrome Or not? Note: A
palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam
or nurses run.
def isPalindrome(string):
left_pos = 0
right_pos = len(string) – 1
def list_sum(num_List):
if len(num_List) == 1:
return num_List[0]
else:
return num_List[0] + list_sum(num_List[1:])
print(list_sum([2, 4, 5, 6, 7]))
Sample Output:
24
48. How to retrieve data from a table in MySQL database through Python code? Explain.
5. retrieve the information by defining a required query string. s = “Select * from dept”
6. fetch the data using fetch() methods and print it. data = c1.fetch(s)
import random
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line(‘test.txt’))
50. Write a Python program to count the number of lines in a text file.
def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(“Number of lines in the file: “,file_lengthy(“test.txt”))
« Previous
Next »
RECOMMENDED COURSES
Self Paced
LEARN MORE
LEARN MORE
12