17 Python Interview Questions and Answers

17 Python Interview Questions and Answers

The tech industry is growing like never before. Every now and then we see new software products are released in the market. So, no matter whether you are a fresher or an experienced Python developer, there are always opportunities waiting for you.

The only requirement is that you have to convince the employer using your skills. It can be possible by appearing in Python programming interviews.

But, you’ve to prepare yourself, otherwise, someone else might get the job. You can either try Python programming challenges or simply overview the frequently asked Python interview questions and answers.

Today, I’m gonna share my personal experience of Python interviews with you. I’ll list the questions they asked me including their possible solutions. So, it will be an ultimate guide for you to get hired as a Python Programmer.

1- Let’s Suppose We Have the Well-Known &Ldquo;Iris” Data Set. Now Retrieve Only Those Records Where &Ldquo;Sepal.Length” Is Greater Than 6 and &Ldquo;Sepal.Width” Is Greater Than 3.3.

Iris Data Set Details:-

Official Website

Download in CSV format


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


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

2- Let’s Say We Have Two Arrays as Mentioned Below. How Can We Add Corresponding Items of Both Arrays?


a = [23,67,1]
b = [98,543,7]


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


Index_0: 121
Index_1: 610
Index_2: 8

3- What Is *args and **kwargs? Give an Example for Each.

Both of these are used to pass a variable number of arguments in a function. We use *args for non-keyword arguments whereas **kwargs is used for keyword-based arguments (e.g. key-value pair).

*args Example:-

def myFun1(*argv): 
    for a in argv: 
myFun1('Welcome', 'to', 'Live Code Stream')


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


username = John Doe
email = example@domain.com
password = Abc123

4- How to Check All the Functions and Properties Available in a Module?

We can pass the module name inside the dir() function to retrieve its functions and properties’ names.

For example:-

let’s say we have a module called m.py with a variable and two user-defined functions.

name = "Juan"

def myFun():

def myFun2():

Now, we can display its properties and functions names inside another file using:

import m


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'myFun', 'myFun2', 'name']

Here you can see that the dir() function also get all the built-in properties and methods.

5- What Are Literals in Python?

In Python, literal is the data/value assigned to a variable or constant. For example, Python has four different types of literals.

  • Numeric Literals
  • String Literals
  • Boolean Literals
  • Special Literals

6- How to Concatenate Two Tuples?

The concatenation of tuples refers to the process through which we can join two or more tuples. For example, let’s suppose we have two tuples:

tuple_1 = (True,"Juan",561)
tuple_2 = (47,100,False)

Now, we can concatenate them together by using a plus + symbol. Basically, this statement will add the elements of tuple_2 at the end of tuple_1.

tuple_1 + tuple_2

Like this:

(True, 'Juan', 561, 47, 100, False)

7- What Is Lambda in Python?

Lambda is a small function in Python that can only process one expression. But, we can add as many parameters as needed.

Generally, it is more suitable to use the lambda function inside of another function.

let’s use the lambda function to multiply 14 with a number passed through an argument.

x = lambda a: a * 14



8- What Is Slicing?

Slicing is a process to retrieve parts of a string, array, list, or tuple. Basically, we pass a start and end index to specify the position of data we’re interested in. It is important to note that the value at the start index is included in the result whereas the value at the end index is excluded.

We can even pass a step value to skip some data. For example, retrieve every other item from an array.

In the below code snippet, the slicing is performed using square brackets []. We passed three arguments and separated them with a colon : symbol. The first parameter specifies the start position of slicing, the second argument is used to mark the end, whereas the last parameter is used to define the step.

countries = ("Germany", "Pakistan", "China", "Turkey", "Australia", "France")



('Germany', 'China', 'Australia')

All of the three parameters of slicing are optional. If we don’t specify the start then Python will assume 0 index as the starting position. Similarly, when we skip the second parameter then the length of array/string/tuple/list will be used. Whereas, by default Python consider 1 as a step.

9- What Are Python Decorators?

Python decorator is a feature that is used to enhance the functionality of an existing function or a class. It is preferred when a developer wants to dynamically update the working of a function without actually modifying it.

Let’s say we have a function that prints the name of the website developer. But, now the requirement is to display a welcome message to the user and then show the developer name.

We can add this functionality with the help of a decorator function.

def welcome_user(func):
    def inner(a, b):
        print("Welcome to Live Code Stream!")
        return func(a, b)
    return inner

def dev_name(first_name, last_name):
    print("Developed By:", first_name, last_name)

dev_name("Juan", "Cruz Martinez")

Here, you can see that welcome_user() is a decorator whereas dev_name() is the main function that we updated dynamically.


Welcome to Live Code Stream!
Developed By: Juan Cruz Martinez

10- Which Algorithm Is Used by sort() and sorted() Functions?

sort() and sorted() functions implement the Timsort algorithm. It is because this sorting algorithm is very stable and efficient. The value of Big O in its worst case is O(N log N).

11- How Do You Debug a Python Program?

By default, Python comes with a built-in debugger known as pdb .

We can start the debugging of any Python file by executing a command something like mentioned below.

python -m pdb your-python-file.py

12- What Is Pickling and Unpickling?

In Python, there is a very popular library called pickle . It is used for object serialization. Meaning that it takes a Python object as input and converts it into a byte stream. This whole process of transforming a Python object is known as pickling.

On the other hand, unpickling is its opposite. Here, a byte stream is accepted as input and transformed into an object hierarchy.

13- What Is List Comprehension? Give an Example.

List Comprehension is a quick way to create a Python list. Instead of manually entering a value for each index, we can simply fill the list by iterating through our data.

Let’s suppose I want to create a list whose each index will contain a letter from my name in sequential order.

name_letters = [ letter for letter in 'Juan Cruz Martinez' ]
print( name_letters )


['J', 'u', 'a', 'n', ' ', 'C', 'r', 'u', 'z', ' ', 'M', 'a', 'r', 't', 'i', 'n', 'e', 'z']

14- (i for I in (54, 6, 71)) Is It a Tuple Comprehension?

No. In Python, there is no such concept of tuple comprehension.

15- What Is Monkey Patching in Python?

The process to dynamically change a class or module at run-time is known as Monkey Patching.


class Website_name: 
     def func(self): 
          print("Live Code Stream")


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


Welcome to Live Code Stream

Did you noticed that I actually called func() method but the output I received was from welcome()?

16- Predict the Output of the Below Code? Explain Your Answer.


class Parent(object):
    x = 53

class Child_1(Parent):

class Child_2(Parent):

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)


53 53 53
53 12 53
89 12 89


The major confusing point in this code occurs in the last print() statement.

Before printing, we just updated the value of x in the Parent class. It automatically updates the value of Child_2.x but not the Child_1.x. It is because we have already set the value of Child_1.x.

In other words, Python tries to use the properties/methods of child class first. It only searches the parent class if the property/method is not found in the child class.

17- How to Display Ancestors of a Given Node in Binary Tree?

Let’s suppose we have this binary tree. Now, retrieve the ancestors of 65 and display them using Python code.

            /    \
          42       3
        /    \
      0       65


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




Practicing for an interview is super important to land your dream job. In today’s article, we covered some popular interview questions but there’s much more you should know. There are entire sites which can prepare you for your next interview, it’s a huge subject, so keep learning.

Thanks for reading!

If you liked what you saw, please support my work!

Juan Cruz Martinez - Author @ Live Code Stream

Juan Cruz Martinez

Juan has made it his mission to help aspiring developers unlock their full potential. With over two decades of hands-on programming experience, he understands the challenges and rewards of learning to code. By providing accessible and engaging educational content, Juan has cultivated a community of learners who share their passion for coding. Leveraging his expertise and empathetic teaching approach, Juan has successfully guided countless students on their journey to becoming skilled developers, transforming lives through the power of technology.