80 Python Interview Questions & Answers
80 Python Interview Questions & Answers
1. What is Python?
List some popular applications of Python in the world of technology.
Python is a widely-used general-purpose, high-level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.
It is used for:
● System Scripting
● Web Development
● Game Development
● Software Development
● Complex Mathematics
2. What are the benefits of using Python language as a tool in the present scenario?
The following are the benefits of using Python language
● Object-Oriented Language
● High-Level Language
● Dynamically Typed language
● Extensive support Libraries
● Presence of third-party modules
● Open source and community development
● Portable and Interactive
● Portable across Operating systems
5. What is the difference between a Mutable data type and an Immutable data type?
● Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary,
etc.
● Immutable data types can not be edited i.e., they can not change at runtime. Eg – String,
Tuple, etc.
28. What is the difference between a shallow copy and a deep copy?
Shallow copy is used when a new instance type gets created and it keeps values that are copied
whereas deep copy stores values that are already copied.
A shallow copy has faster program execution whereas a deep copy makes it slow.
29. Which sorting technique is used by sort() and sorted() functions of python?
Python uses the Tim Sort algorithm for sorting. It’s a stable sorting whose worst case is O(N log
N). It’s a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform
well on many kinds of real-world data.
P1 = address(“Albert street”,20)
p1.myfunc()
58. What is comprehension in Python?
It provide us with the short and a concise way to construct a new sequences
[such as a list set dictionary etc]
using sequences which have been already defined Python supports
four types of a comprehension
● list comprehension
● dictionary comprehension
● set comprehension
● generator comprehension
A. List comprehension-
● it provide an elegant way to create a new list.The following is the basic structure of a list
comprehension
● output list= [ output_execution for var in input_list if (var satisfy this condition)]
● Note - list comprehension may or may not contain and if condition list comprehension can
contain multiple for nested list conference comprehension
1. example one suppose we want to create an output list which contains only the even number
which are present in the input list let's see how to do this using for loops and list comprehension
and decide which method suits better
#without using list comprehension
Input_list = [1, 2, 3, 4, 4, 5, 6, 7,7]
Output_list=[ ]
#look for constructing output
for var in input_list:
If var % 2 ==0:
Output_list.append(var)
print(“Output list using for loop, output_list)
2 Suppose we want to create an output list which contains squares of all the numbers from 1 to 9
let's see how to do this using for loops and list comprehension
# Constructing output list using for loop
output list is equal to[]
for war in range(1, 10):
output_list.append(var ** 2):
print(“Output list using for loops: “,output_list )
output = output list using for loop : [1 4 9 16 25 36 49 64 81]
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
Example #1: Suppose we want to create an output dictionary which contains only the odd
numbers that are present in the input list as keys and their cubes as values. Let’s see how to do
this using for loops and dictionary comprehension.
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
# Using loop for constructing output dictionary
for var in input_list:
if var % 2 != 0:
output_dict[var] = var**3
print("Output Dictionary using for loop:", output_dict )
Output: Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
# Using Dictionary comprehensions
# for constructing output dictionary
input_list = [1,2,3,4,5,6,7]
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
Output: Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343}
Example #2: Given two lists containing the names of states and their corresponding capitals,
construct a dictionary which maps the states with their respective capitals. Let’s see how to do this
using for loops and dictionary comprehension.
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
output_dict = {}
# Using loop for constructing output dictionary
for (key, value) in zip(state, capital):
output_dict[key] = value
print("Output Dictionary using for loop:", output_dict)
Output Output Dictionary using for loop: {'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai',
'Rajasthan': 'Jaipur'}
C. set comprehension:
Set comprehensions are pretty similar to list comprehensions. The only difference between them
is that set comprehensions use curly brackets { }. Let’s look at the following example to
understand set comprehensions.
Example #1 : Suppose we want to create an output set which contains only the even numbers that
are present in the input list. Note that set will discard all the duplicate values. Let’s see how we
can do this using for loops and set comprehension.
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
# Using loop for constructing output set
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)
Output: Output Set using for loop: {2, 4, 6}
D. generator comprehension
Generator Comprehensions are very similar to list comprehensions. One difference between them
is that generator comprehensions use circular brackets whereas list comprehensions use square
brackets. The major difference between them is that generators don’t allocate memory for the
whole list. Instead, they generate each value one by one which is why they are memory efficient.
Let’s look at the following example to understand generator comprehension:
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_gen = (var for var in input_list if var % 2 == 0)
print("Output values using generator comprehensions:", end = ' ')
for var in output_gen:
print(var, end = ' ')
Output: Output values using generator comprehensions: 2 4 4 6
● Creating Decorators
With these prerequisites out of the way, let's go ahead and create a simple decorator that will
convert a sentence to uppercase. We do this by defining a wrapper inside an enclosed function.
As you can see it is very similar to the function inside another function that we created earlier.
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
Our decorator function takes a function as an argument, and we shall, therefore, define a function
and pass it to our decorator. We learned earlier that we could assign a function to a variable. We'll
use that trick to call our decorator function.
def say_hi():
return 'hello there'
decorate = uppercase_decorator(say_hi)
decorate()
Output 'HELLO THERE'
However, Python provides a much easier way for us to apply decorators. We simply use the @
symbol before the function we'd like to decorate. Let's show that in practice below.
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
Output 'HELLO THERE'
@split_string
@uppercase_decorator
def say_hi():
return 'hello there'
say_hi()
['HELLO', 'THERE']
From the above output, we notice that the application of decorators is from the bottom up. Had we
interchanged the order, we'd have seen an error since lists don't have an upper attribute. The
sentence has first been converted to uppercase and then split into a list.
@decorator_with_arguments
def cities(city_one, city_two):
print("Cities I love are {0} and {1}".format(city_one, city_two))
cities("Nairobi", "Accra")
Output My arguments are: Nairobi, Accra
Cities I love are Nairobi and Accra
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print("No arguments here.")
function_with_no_argument()
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print(a, b, c)
function_with_arguments(1,2,3)
function_with_keyword_arguments(first_name="Derrick", last_name="Mwiti")
The positional arguments are ()
The keyword arguments are {'first_name': 'Derrick', 'last_name': 'Mwiti'}
This has shown keyword arguments
pandas = "Pandas"
@decorator_maker_with_arguments(pandas, "Numpy","Scikit-learn")
def decorated_function_with_arguments(function_arg1, function_arg2,function_arg3):
print("This is the decorated function and it only knows about its arguments: {0}"
" {1}" " {2}".format(function_arg1, function_arg2,function_arg3))
● Debugging Decorators
As we have noticed, decorators wrap functions. The original function name, its docstring, and
parameter list are all hidden by the wrapper closure: For example, when we try to access the
decorated_function_with_arguments metadata, we'll see the wrapper closure's metadata. This
presents a challenge when debugging.
decorated_function_with_arguments.__name__
'wrapper'
decorated_function_with_arguments.__doc__
'This is the wrapper function'
In order to solve this challenge Python provides a functools.wraps decorator. This decorator
copies the lost metadata from the undecorated function to the decorated closure. Let's show how
we'd do that.
import functools
def uppercase_decorator(func):
@functools.wraps(func)
def wrapper():
return func().upper()
return wrapper
@uppercase_decorator
def say_hi():
"This will say hi"
return 'hello there'
say_hi()
'HELLO THERE'
When we check the say_hi metadata, we notice that it is now referring to the function's metadata
and not the wrapper's metadata.
say_hi.__name__
'say_hi'
say_hi.__doc__
'This will say hi'
It is advisable and good practice to always use functools.wraps when defining decorators. It will
save you a lot of headache in debugging.
63. What are the popular Python libraries used in Data analysis?
Some of the popular libraries of Python used for Data analysis are:
● Pandas: Powerful Python Data Analysis Toolkit
● SciKit: This is a machine learning library in Python.
● Seaborn: This is a statistical data visualization library in Python.
● SciPy: This is an open source system for science, mathematics and
● engineering implemented in Python.
69. How can you randomize the items of a list in place in Python?
This can be easily achieved by using the Shuffle() function from the random library as shown
below:
from random import shuffle
List = ['He', 'Loves', 'To', 'Code', 'In', 'Python']
shuffle(List)
print(List)
Output: [‘Loves’,’He’ ,’To ,’In’, ‘Python’,’Code’]
70. What are negative indexes and why are they used?
To access an element from ordered sequences, we simply use the index of the element, which is
the position number of that particular element. The index usually starts from 0, i.e., the first
element has index 0, the second has 1, and so on.
Python Indexing
When we use the index to access elements from the end of a list, it’s called reverse indexing. In
reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’.
The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are
called negative indexes.