Top 50 Python Interview Questions and Answers
Top 50 Python Interview Questions and Answers
1.
1. How will you improve the performance of a
program in Python?
There are many ways to improve the performance of a Python program. Some of
these are as follows:
● Data Structure: We have to select the right data structure for our
purpose in a Python program.
In the above line we can replace encoding with the encoding that we want
to use.
Some other tools to find bugs in Python code are pylint and pyflakes.
III. Size: A Tuple takes much lesser space than a List in Python.
V. Use case: Since Tuple is immutable, we can use it in cases like
Dictionary creation. Whereas, a List is preferred in the use case where
data can alter.
Since some of the objects passed as reference are mutable, we can change
those objects in a method. But for an Immutable object like String, any
change done within a method is not reflected outside.
Numeric types: These are the data types used to represent numbers in
Python.
byte array: like bytes, but mutable (see below); only available in Python 3.x
list: This is a sequence of objects.
E.g. the set of built-in exception names, the set of built-in names, local
names in a function
E.g.
>>> fname="John"
>>> lname="Ray"
E.g.
>>> ''.join(['John','Ray'])
'JohnRay'
... pass
E.g. In following example we are getting a substring out of the name John.
>>> name="John"
>>> name[1:3]
16.
'oh'
>>> name="John"
>>> name[:2]
'Jo'
If we do not give second index, then it defaults to the size of the String.
>>> name="John"
>>> name[3:]
'n'
The docstring for a code object can be accessed from the '__doc__'
attribute of that object.
II. Test case: This is main unit test that we run on a piece of code. We
can use Test case base class to create new test cases.
III. Test suite: We can aggregate our unit test cases in a Test suite.
IV. Test runner: We use test runner to execute unit tests and produce
reports of the test run.
A Generator is more compact than an Iterator due to the fact that _iter_()
and next() functions are automatically created in a Generator.
Also within a Generator code, local variables and execution state are saved
between multiple calls. Therefore, there is no need to add extra
variables like self.index etc to keep track of iteration.
Object._new_
Object._init_
Object._del_
The above mentioned lambda expression takes two arguments and returns
their sum.
II. Large library: There is a large library for utilities in Python that
can be used for different kinds of applications.
V. Complex built-in Data types: Python has built-in Complex data
types like list, set, dict etc. These data types give very good
performance as well as save time in coding new features.
24.
Flask does not provide a data abstraction layer or form validation by default. We
can use external libraries on top of Flask to perform such tasks.
27.
None is a reserved keyword used in Python for null objects. It is neither a null
value nor a null pointer. It is an actual object in Python. But there is only
one instance of None in a Python environment.
During comparison we have to use “is” operator instead of “==” for None.
28.
In Python, we have a built-in function zip() that can be used to aggregate all the
Iterable objects of an Iterator.
We can use it to aggregate Iterable objects from two iterators as well. E.g.
print a, b
Output:
a1 b2 c3
By using zip() function we can divide our input data from different sources into
fixed number of sets.
10// 4 = 2
-10//4 = -3
30.
Python uses most of the Object Oriented programming concepts. But we can
also do functional programming in Python. As per the opinion of experts,
Python is a multi-paradigm programming language.
To retrieve data from a database we have to make use of the module available
for that database. For MySQL database, we import MySQLdb module in our
Python script.
Once we establish the connection, we can open a cursor with cursor() function.
On an open cursor, we can run fetch() function to execute queries and
retrieve data from the database tables.
34.
In Python, we get a built-in sequence called list. We can call standard functions
like append() and extend() on a list.
In append() we have to add items one by one. But in extend() multiple items
from another list can be added at the same time.
35.
If we do not want to stop the program, we can just catch the error condition,
print a message and continue with our program.
E.g. In following code snippet we are catching the error and continuing with the
default value of age.
#!/usr/bin/python try:
age=18+'duration'
except:
age=18
print(age)
Both split() function and slicing work on a String object. By using split() function,
we can get the list of words from a String.
>>> issubclass(bool,int)
True
38.
In Python, we can use the debugger pdb for debugging the code. To start
debugging we have to enter following lines on the top of a Python script.
After adding these lines, our code runs in debug mode. Now we can use
commands like breakpoint, step through, step into etc for debugging.
39.
Python provides a profiler called cProfile that can be used for profiling Python
code.
It gives use the number of function calls as well as the total time taken to run the
script.
We can even write the profile results to a file instead of standard out.
40.
E.g.
True
False
This common module can be imported in all the modules in which we want to
share the variables.
In this way, all the shared variables will be in one module and available for
sharing with any new module as well.
42.
Python provides built-in functions that can be used for Functional programming.
Some of these functions are:
I. Map()
The enumerate() function returns an iterator that gives (0, item[0]). E.g.
>>> thelist=['a','b']
0 a
1 b
44.
In addition to that we have to add following line as the first line in a Python script
file.
#!/usr/local/bin/python
This will tell Unix to use Python interpreter to execute the script.
45.
Some of the popular libraries of Python used for Data analysis are:
>>> thelist=['a','b']
[]
Even though the list has only 2 elements, the call to thelist with index 3 does not
give any index error.
47.
>>>name=’John Smith’
John Smith
This is an example of Slicing. Since we are slicing at the same index, the first
name[:5] gives the substring name upto 5th location excluding 5th location.
The name[5:] gives the rest of the substring of name from the 5th location.
So we get the full name as output.
48.
In Python, we can use dict data type to store key value pairs. In this example,
customer name can be the key and their location can be the value in a dict
data type.
Dictionary is an efficient way to store data that can be looked up based on a key.