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 “Iris” data set. Now retrieve only those records where “Sepal.Length” is greater than 6 and “Sepal.Width” is greater than 3.3.
Iris Data Set Details:-
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): print(j) print()
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
**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).
def myFun1(*argv): for a in argv: print(a) myFun1('Welcome', 'to', 'Live Code Stream')
Welcome to Live Code Stream
def myFun2(**kwargs): for k, v in kwargs.items(): print ("%s = %s" %(k, v)) myFun2(username = 'John Doe', email = 'email@example.com', password = 'Abc123')
username = John Doe email = firstname.lastname@example.org 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.
let’s say we have a module called m.py with a variable and two user-defined functions.
name = "Juan" def myFun(): return def myFun2(): return
Now, we can display its properties and functions names inside another file using:
import m print(dir(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_2
(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 print(x(3))
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") print(countries[0:5:2])
('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 @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
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
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']
(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()" obj.func()
Welcome to Live Code Stream
Did you noticed that I actually called
func() method but the output I received was from
16- Predict the output of the below code? Explain your answer.
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)
53 53 53 53 12 53 89 12 89
The major confusing point in this code occurs in the last
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
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.
58 / \ 42 3 / \ 0 65 / 17
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)
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!