What are the common Python interview questions? The tech industry is growing at an unprecedented rate. Every now and then, we see new software products being released in the market. So, whether you’re a newbie or an experienced Python developer, there’s always a chance waiting for you.
The only requirement is that you have to convince the employer with your skills. This can be done by attending a Python programming interview.
However, you have to be prepared, otherwise, someone else might get the job. You can either try the Python programming challenge or simply outline common Python interview questions and answers.
Today, in this collection of Python common interview questions and answers, I would like to share with you my personal Python interview experience. I will make a list of the problems they ask me, including their possible solutions. So, this will be your ultimate guide to getting hired as a Python programmer.
Suppose we have the well-known “Iris” dataset. Only those records with “Sepal.Length” greater than 6 and “Sepal.Width” greater than 3.3 are now retrieved.
Iris Dataset Details:-
Python Interview Questions and Answer Parsing Code:-
import pandas as pd
iris = pd.read_csv('iris.csv')
df = pd.DataFrame(iris)
for i, j in df.iterrows():
if (j['sepal_length'] > 6) & (j['sepal_width'] > 3.3):
print(j)
print()
Output:-
sepal_length 7.2
sepal_width 3.6
petal_length 6.1
petal_width 2.5
species virginica
Name: 109, dtype: object
sepal_length 7.7
sepal_width 3.8
petal_length 6.7
petal_width 2.2
species virginica
Name: 117, dtype: object
sepal_length 7.9
sepal_width 3.8
petal_length 6.4
petal_width 2
species virginica
Name: 131, dtype: object
sepal_length 6.3
sepal_width 3.4
petal_length 5.6
petal_width 2.4
species virginica
Name: 136, dtype: object
sepal_length 6.2
sepal_width 3.4
petal_length 5.4
petal_width 2.3
species virginica
Name: 148, dtype: object
Let’s say we have two arrays, as described below. How do we add the corresponding of two arrays?
Array:-
a = [23,67,1]
b = [98,543,7]
Code:-
import numpy as np
a = np.array([23,67,1])
b = np.array([98,543,7])
c = np.sum((a,b), axis=0)
j = 0
for i in c:
print("Index_" + str(j) + ":", i)
j += 1
Output:-
Index_0: 121
Index_1: 610
Index_2: 8
What is AND? Let’s take an example each.*args
**kwargs
What are the common Python interview questions? Both of these are used to pass a variable number of arguments in a function. We use non-keyword arguments, but keyword-based arguments (e.g. key-value pairs).*args**kwargs
*ARGS Example:
–
def myFun1(*argv):
for a in argv:
print(a)
myFun1('Welcome', 'to', 'Live Code Stream')
Output:-
Welcome
to
Live Code Stream
**kwargs
Example:-
def myFun2(**kwargs):
for k, v in kwargs.items():
print ("%s = %s" %(k, v))
myFun2(username = 'John Doe', email = 'example@domain.com', password = 'Abc123')
Output:-
username = John Doe
email = example@domain.com
password = Abc123
How do I check all the features and attributes available in the module?
Python Common Interview Questions and Answers Collection: We can pass the module name inside the function to retrieve the name of its function and property.dir()
For example:-
Let’s say we have a module called m.py that contains a variable and two user-defined functions.
name = "Juan"
def myFun():
return
def myFun2():
return
Now we can display its properties and function names in another file with the following command:
import m
print(dir(m))
Output:-
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'myFun', 'myFun2', 'name']
Here you can see that the function also fetches all the built-in properties and methods.dir()
What are literals in Python?
In Python, literals are data/values assigned to variables or constants. For example, Python has four different types of scripts.
- Digital text
- String literals
- Boolean text
- Special text
How do I connect two tuples?
Concatenation of tuples refers to the process by which we can connect two or more tuples. For example, let’s say we have two tuples:
tuple_1 = (True,"Juan",561)
tuple_2 = (47,100,False)
Now we can connect them together using the plus sign. Basically, the statement will be used in the .+
tuple_2
tuple_1
tuple_1 + tuple_2
Like this:
(True, 'Juan', 561, 47, 100, False)
What is lambda in Python?
Lambda is a small function in Python that can only handle one expression. However, we can add as many parameters as we want.
In general, it’s more appropriate to use a lambda function inside another function.
Let’s use the lambda function to multiply 14 by the number passed through the arguments.
x = lambda a: a * 14
print(x(3))
Output:-
42
What is a slice?
Slicing is the process of retrieving a string, array, list, or part of a tuple. Basically, we pass a start and end index to specify the location of the data we are interested in. It is important to note that the value at the beginning index is included in the results, while the value at the end index is excluded.
We can even pass a step value to skip some data. For example, retrieving all other items from an array.
In the code snippet below, the slice is performed using square brackets [].
We passed three arguments and separated them with colons. The first parameter specifies where the slice begins, the second parameter marks the end, and the last parameter defines the step.:
countries = ("Germany", "Pakistan", "China", "Turkey", "Australia", "France")
print(countries[0:5:2])
Output:-
('Germany', 'China', 'Australia')
All three parameters of the slice are optional. If we don’t specify a start, then Python will assume a 0 index as the starting position. Again, when we skip the second parameter, the length of the array/string/tuple/list will be used. By default, Python treats 1 as a step.
What is a Python decorator?
A Python decorator is a feature that enhances the functionality of an existing function or class. This is preferred when developers want to dynamically update the work of a feature without actually modifying it.
Let’s say we have a function that prints the name of a website developer. However, the requirement now is to display a welcome message to the user and then the developer name.
We can add this with the help of decorator functions.
def welcome_user(func):
def inner(a, b):
print("Welcome to Live Code Stream!")
return func(a, b)
return inner
@welcome_user
def dev_name(first_name, last_name):
print("Developed By:", first_name, last_name)
dev_name("Juan", "Cruz Martinez")
Here you can see that it’s a decorator, and it’s the main function that we’re dynamically updating.welcome_user()
dev_name()
Output:-
Welcome to Live Code Stream!
Developed By: Juan Cruz Martinez
Which algorithm is used for the 10- sum function?sort()
sorted()
What are the common Python interview questions? The sum function implements the Timsort algorithm. This is because this sorting algorithm is very stable and efficient. The value of O, which in its worst case is O(N logn).sort()
sorted()
How do I debug a Python program?
By default, Python comes with a built-in debugger called pdb.
We can start debugging any Python file by executing the command described below.
python -m pdb your-python-file.py
What is Pickling and Unpickling?
Python Interview Questions and Answer Analysis: In Python, there is a very popular library called pickle. It is used for object serialization. This means that it takes a Python object as input and converts it into a byte stream. The whole process of converting a Python object is called pickling.
Unpickling, on the other hand, is the opposite of it. Here, a stream of bytes is accepted as input and converted to an object hierarchy.
What is List Comprehension? Here’s an example.
Collection of Python Common Interview Questions and Answers: List Comprehension is a quick way to create a list in Python. Instead of manually entering values for each index, we can simply populate the list by iterating over the data.
Let’s say I want to create a list whose each index will contain one letter from my name in order.
name_letters = [ letter for letter in 'Juan Cruz Martinez' ]
print( name_letters )
Output:-
['J', 'u', 'a', 'n', ' ', 'C', 'r', 'u', 'z', ' ', 'M', 'a', 'r', 't', 'i', 'n', 'e', 'z']
Is it a tuple understood?(i for i in (54, 6, 71))
No. In Python, there is no tuple that understands such a concept.
What is Monkey Patching in Python?
The process of dynamically changing a class or module at runtime is called Monkey Patching.
website_name.py
class Website_name:
def func(self):
print("Live Code Stream")
main.py
import website_name
def welcome(self):
print("Welcome to Live Code Stream")
# replacing address of "func" with "welcome"
website_name.Website_name.func = welcome
obj = website_name.Website_name()
# calling function "func()" whose address got replaced with function "welcome()"
obj.func()
Output:-
Welcome to Live Code Stream
Have you ever noticed that I actually called the method, but the output I received came from?func()
welcome()
Predict the output of the following code? Explain your answer.
Code:-
class Parent(object):
x = 53
class Child_1(Parent):
pass
class Child_2(Parent):
pass
print(Parent.x, Child_1.x, Child_2.x)
Child_1.x = 12
print(Parent.x, Child_1.x, Child_2.x)
Parent.x = 89
print(Parent.x, Child_1.x, Child_2.x)
Output:-
53 53 53
53 12 53
89 12 89
Python Interview Questions and Answers Analysis:-
The main point of confusion in this code is in the last statement.print()
We just updated the values in the class before printing. It automatically updates the value of , but not . This is because we have already set the value of .x
Parent
Child_2.x
Child_1.x
Child_1.x
In other words, Python tries to use the properties/methods of the subclass first. If the property/method is not found in the child class, it will only search the parent class.
How do I show the ancestors of a given node in a binary tree?
What are the common Python interview questions? Let’s say we have this binary tree. Now, retrieve the ancestors of 65 and display them using Python code.
58
/ \
42 3
/ \
0 65
/
17
Code:-
class Node:
# Create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def displayAncestors(root, target):
# Base case
if root == None:
return False
if root.data == target:
return True
# Print this node if target is present in either left or right subtree
if (displayAncestors(root.left, target) or
displayAncestors(root.right, target)):
print(root.data)
return True
# Else
return False
# Test above function
root = Node(58)
root.left = Node(42)
root.right = Node(3)
root.left.left = Node(0)
root.left.right = Node(65)
root.left.left.left = Node(17)
displayAncestors(root, 65)
Output:-
42
58
Python Common Interview Questions and Answers Collection Conclusion
Practice interviews are very important to find your dream job. In today’s article, we have covered some of the popular interview questions, but you should know more about them. There are plenty of websites out there that will prepare you for your next interview, and it’s a huge topic, so keep learning.
Thanks for reading!