The 23 Top Python Interview Questions & Answers For 2024
The 23 Top Python Interview Questions & Answers For 2024
These are some of the questions you might encounter during an entry-level Python
interview.
Lists and tuples are fundamental Python data structures with distinct characteristics and use
cases.
List:
Example:
a_list.append("Session")
POWERED BY
Tuple:
POWERED BY
Purpose:
Example:
We have created a `book_shop` class and added the constructor and `book()` function. The
constructor will store the book title name and the `book()` function will print the book name.
To test our code we have initialized the `b` object with “Sandman” and executed the `book()`
function.
class book_shop:
# constructor
self.title = title
# Sample method
def book(self):
print('The tile of the book is', self.title)
b = book_shop('Sandman')
b.book()
POWERED BY
● Definition: Mutable data types are those that can be modified after
their creation.
● Examples: List, Dictionary, Set.
● Characteristics: Elements can be added, removed, or changed.
● Use Case: Suitable for collections of items where frequent updates
are needed.
Example:
# List Example
a_list = [1, 2, 3]
a_list.append(4)
# Dictionary Example
POWERED BY
Example:
# Numeric Example
a_num = 10
print(a_num) # Output: 20
# String Example
a_str = "hello"
# Tuple Example
a_tuple = (1, 2, 3)
# a_tuple[0] = 4 # This will raise a TypeError
POWERED BY
List
List comprehension offers one-liner syntax to create a new list based on the values of the
existing list. You can use a `for loop` to replicate the same thing, but it will require you to
write multiple lines, and sometimes it can get complex.
List comprehension eases the creation of the list based on existing iterable.
my_list
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
POWERED BY
Dictionary
Similar to a List comprehension, you can create a dictionary based on an existing table with
a single line of code. You need to enclose the operation with curly brackets `{}`.
my_dict
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
POWERED BY
Tuple
It is a bit different for Tuples. You can create Tuple comprehension using round brackets `()`,
but it will return a generator object, not a tuple comprehension.
You can run the loop to extract the elements or convert them to a list.
my_tuple = (i for i in range(1, 10))
my_tuple
POWERED BY
Monkey patching in Python is a dynamic technique that can change the behavior of the code
at run-time. In short, you can modify a class or module at run-time.
Example:
Instead of displaying “patch() is being called”, it has displayed “monk_p() is being called”.
class monkey:
def patch(self):
def monk_p(self):
print ("monk_p() is being called")
monkey.patch = monk_p
obj = monkey()
obj.patch()
POWERED BY
The `with` statement is used for exception handling to make code cleaner and simpler. It is
generally used for the management of common resources like creating, editing, and saving a
file.
Example:
Instead of writing multiple lines of open, try, finally, and close, you can create and write a text
file using the `with` statement. It is simple.
POWERED BY
`try:` and `except:` are commonly known for exceptional handling in Python, so where does
`else:` come in handy? `else:` will be triggered when no exception is raised.
Example:
try:
division = num1/num2
except:
print('Invalid input!')
else:
print('Division is successful.')
## Try 1 ##
# Enter Numerator: 2
# Enter Denominator: d
# Invalid input!
## Try 2 ##
# Enter Numerator: 2
# Enter Denominator: 1
# Division is successful.
POWERED BY
Take the Python Fundamentals skill track to gain the foundational skills you need to become
a Python programmer.
Decorators in Python are a design pattern that allows you to add new functionality to an
existing object without modifying its structure. They are commonly used to extend the
behavior of functions or methods.
Example:
def my_decorator(func):
def wrapper():
func()
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Hello!
POWERED BY
9. What are context managers in Python and how are they implemented?
Context managers in Python are used to manage resources, ensuring that they are properly
acquired and released. The most common use of context managers is the with statement.
Example:
class FileManager:
self.filename = filename
self.mode = mode
def __enter__(self):
return self.file
f.write('Hello, world!')
POWERED BY
In this example, the FileManager class is a context manager that ensures the file is
properly closed after it is used within the with statement.
For those focused more on data science applications of Python, these are some questions
you may encounter.
10. What are the advantages of NumPy over regular Python lists?
Memory
For example, if you create a list and a Numpy array of a thousand elements. The list will
consume 48K bytes, and the Numpy array will consume 8k bytes of memory.
Speed
Numpy arrays take less time to perform the operations on arrays than lists.
For example, if we are multiplying two lists and two Numpy arrays of 1 million elements
together. It took 0.15 seconds for the list and 0.0059 seconds for the array to operate.
Vesititly
Numpy arrays are convenient to use as they offer simple array multiple, addition, and a lot
more built-in functionality. Whereas Python lists are incapable of running basic operations.
Merge
Merge two DataFrames named series objects using the unique column identifier.
It requires two DataFrame, a common column in both DataFrame, and “how” you want to
join them together. You can left, right, outer, inner, and cross join two data DataFrames. By
default, it is an inner join.
POWERED BY
Join
Join the DataFrames using the unique index. It requires an optional `on` argument that can
be a column or multiple column names. By default, the join function performs a left join.
df1.join(df2)
POWERED BY
Concatenate
Concatenate joins two or multiple DataFrames along a particular axis (rows or columns). It
doesn't require an `on` argument.
pd.concat(df1,df2)
POWERED BY
We can identify missing values in the DataFrame by using the `isnull()` function and then
applying `sum()`. `Isnull()` will return boolean values, and the sum will give you the number
of missing values in each column.
In the example, we have created a dictionary of lists and converted it into a pandas
DataFrame. After that, we used isnull().sum() to get the number of missing values in each
column.
import pandas as pd
import numpy as np
# dictionary of lists
# creating a DataFrame
df = pd.DataFrame(dict)
df.isnull().sum()
# id 1
# Age 2
# Score 1
POWERED BY
Note: make sure you are working with a larger dataset while using the `dropna()` function.
#fillna
df.fillna(method ='bfill')
# Interpolate
POWERED BY
Become a professional data scientist by taking the Data Scientist with Python career track. It
includes 25 courses and six projects to help you learn all the fundamentals of data science
with the help of Python libraries.
13. Which all Python libraries have you used for visualization?
Data visualization is the most important part of data analysis. You get to see your data in
action, and it helps you find hidden patterns.
1. Matplotlib
2. Seaborn
3. Plotly
4. Bokeh
In Python, we generally use Matplotlib and seaborn to display all types of data visualization.
With a few lines of code, you can use it to display scatter plot, line plot, box plot, bar chart,
and many more.
For interactive and more complex applications, we use Plotly. You can use it to create
colorful interactive graphs with a few lines of code. You can zoom, apply animation, and
even add control functions. Plotly provides more than 40 unique types of charts, and we can
even use them to create a web application or dashboard.
Bokeh is used for detailed graphics with a high level of interactivity across large datasets.
If you have a Python coding interview coming up, preparing questions similar to these can
help you impress the interviewer.
14. How can you replace string space with a given character in Python?
It is a simple string manipulation challenge. You have to replace the space with a specific
character.
Example 1: a user has provided the string “l vey u” and the character “o”, and the output will
be “loveyou”.
Example 2: a user has provided the string “D t C mpBl ckFrid yS le” and the character “a”,
and the output will be “DataCampBlackFridaySale”.
In the `str_replace()` function, we will loop over each letter of the string and check if it is
space or not. If it consists of space, we will replace it with the specific character provided by
the user. Finally, we will be returning the modified string.
def str_replace(text,ch):
result = ''
for i in text:
if i == ' ':
i = ch
result += i
return result
ch = "a"
str_replace(text,ch)
# 'DataCampBlackFridaySale'
POWERED BY
15. Given a positive integer num, write a function that returns True if
num is a perfect square else False.
This has a relatively straightforward solution. You can check if the number has a perfect
square root by:
Test 1
Test 2
def valid_square(num):
square = int(num**0.5)
check = square**2==num
return check
valid_square(10)
# False
valid_square(36)
# True
POWERED BY
To pass this challenge, you have to first calculate n factorial (n!) and then calculate the
number of training zeros.
Finding factorial
In the first step, we will use a while loop to iterate over the n factorial and stop when the n is
equal to 1.
In the second step, we will calculate the trailing zero, not the total number of zeros. There is
a huge difference.
7! = 5040
POWERED BY
The seven factorials have a total of two zeros and only one trailing zero, so our solution
should return 1.
def factorial_trailing_zeros(n):
fact = n
while n > 1:
fact *= n - 1
n -= 1
result = 0
for i in str(fact)[::-1]:
if i == "0":
result += 1
else:
break
return result
factorial_trailing_zeros(10)
# 2
factorial_trailing_zeros(18)
# 3
POWERED BY
Take the essential practicing coding interview questions course to prepare for your next
coding interviews in Python.
Below, we’ve picked out some of the questions you might expect from the most sought-after
roles in the industries, those at Meta, Amazon, Google, and the like.
The exact questions you’ll encounter at Meta depend largely on the role. However, you might
expect some of the following:
You are provided with a large string and a dictionary of the words. You have to find if the
input string can be segmented into words using the dictionary or not.
Image by Author
The solution is reasonably straightforward. You have to segment a large string at each point
and check if the string can be segmented to the words in the dictionary.
first_str = s[0:i]
if first_str in dictionary:
second_str = s[i:]
if (
not second_str
or second_str in dictionary
or can_segment_str(second_str,
dictionary)
):
return True
return False
s = "datacamp"
# True
POWERED BY
Given an integer sorted array in increasing order, remove the duplicate numbers such that
each unique element appears only once. Make sure you keep the final order of the array the
same.
It is impossible to change the length of the array in Python, so we will place the result in the
first part of the array. After removing duplicates, we will have k elements, and the first k
elements in the array should hold the results.
Solution:
1. Run the loop for the range of 1 to the size of the array.
2. Check if the previous number is unique or not. We are comparing
previous elements with the current one.
3. If it is unique, update the array using insertIndex, which is 1 at the
start, and add +1 to the insertIndex.
4. Return insertIndex as it is the k.
This question is relatively straightforward once you know how. If you put more time into
understanding the statement, you can easily come up with a solution.
def removeDuplicates(array):
size = len(array)
insertIndex = 1
if array[i - 1] != array[i]:
array[insertIndex] = array[i]
insertIndex = insertIndex + 1
return insertIndex
array_1 = [1,2,2,3,3,4]
removeDuplicates(array_1)
# 4
array_2 = [1,1,3,4,5,6,6]
removeDuplicates(array_2)
# 5
POWERED BY
You are provided with the list of stock prices, and you have to return the buy and sell price to
make the highest profit.
Note: We have to make maximum profit from a single buy/sell, and if we can’t make a profit,
we have to reduce our losses.
Example 1: stock_price = [8, 4, 12, 9, 20, 1], buy = 4, and sell = 20. Maximizing the profit.
Example 2: stock_price = [8, 6, 5, 4, 3, 2, 1], buy = 6, and sell = 5. Minimizing the loss.
Solution:
1. We will calculate the global profit by subtracting global sell (the first
element in the list) from current buy (the second element in the list).
2. Run the loop for the range of 1 to the length of the list.
3. Within the loop, calculate the current profit using list elements and
current buy value.
4. If the current profit is greater than the global profit, change the global
profit with the current profit and global sell to the i element of the list.
5. If the current buy is greater than the current element of the list,
change the current buy with the current element of the list.
6. In the end, we will return global buy and sell value. To get global buy
value, we will subtract global sell from global profit.
The question is a bit tricky, and you can come up with your unique algorithm to solve the
problems.
def buy_sell_stock_prices(stock_prices):
current_buy = stock_prices[0]
global_sell = stock_prices[1]
global_profit = global_sell - current_buy
global_profit = current_profit
global_sell = stock_prices[i]
current_buy = stock_prices[i]
stock_prices_1 = [10,9,16,17,19,23]
buy_sell_stock_prices(stock_prices_1)
# (9, 23)
stock_prices_2 = [8, 6, 5, 4, 3, 2, 1]
buy_sell_stock_prices(stock_prices_2)
# (6, 5)
POWERED BY
Amazon Python interview questions can vary greatly but could include:
You have been provided with the list of positive integers from 1 to n. All the numbers from 1
to n are present except x, and you must find x.
Example:
4 5 3 2 8 1 6
● n=8
● missing number = 7
def find_missing(input_list):
sum_of_elements = sum(input_list)
n = len(input_list) + 1
actual_sum = (n * ( n + 1 ) ) / 2
list_1 = [1,5,6,3,4]
find_missing(list_1)
# 2
POWERED BY
Write a function that returns True if there is a Pythagorean triplet that satisfies a2+ b2 = c2
Example:
Input Output
[3, 1, 4, 6, 5] True
Solution:
def checkTriplet(array):
n = len(array)
for i in range(n):
array[i] = array[i]**2
array.sort()
s = set()
if (array[i] - array[j]) in s:
return True
s.add(array[j])
return False
arr = [3, 2, 4, 6, 5]
checkTriplet(arr)
# True
POWERED BY
22. How many ways can you make change with coins and a total amount?
We need to create a function that takes a list of coin denominations and total amounts and
returns the number of ways we can make the change.
In the example, we have provided coin denominations [1, 2, 5] and the total amount of 5. In
return, we got five ways we can make the change.
Image by Author
Solution:
solution[0] = 1
return solution[len(solution) - 1]
denominations = [1,2,5]
amount = 5
solve_coin_change(denominations,amount)
# 4
POWERED BY
As with the other companies mentioned, Google Python interview questions will depend on
the role and level of experience. However, some common questions include:
An iterator is an object that we can use to iterate over iterable objects like lists, dictionaries,
tuples, and sets.
The generator is a function similar to a normal function, but it generates a value using the
yield keyword instead of return. If the function body contains yield, it automatically becomes
a generator.
Read more about Python iterators and generators in our full tutorial.
24. Given an array arr[], find the maximum j – i such that arr[j] > arr[i]
This question is quite straightforward but requires special attention to detail. We are provided
with an array of positive integers. We have to find the maximum difference between j-i where
array[j] > array[i].
Examples:
Solution:
1. Calculate the length of the array and initiate max difference with -1.
2. Run two loops. The outer loop picks elements from the left, and the
inner loop compares the picked elements with elements starting from
the right side.
3. Stop the inner loop when the element is greater than the picked
element and keep updating the maximum difference using j - I.
def max_index_diff(array):
n = len(array)
max_diff = -1
j = n - 1
max_diff = j - i
j -= 1
return max_diff
array_1 = [20,70,40,50,12,38,98]
max_index_diff(array_1)
# 6
POWERED BY
Ternary operators are also known as conditional expressions. They are operators that
evaluate expression based on conditions being True and False.
You can write conditional expressions in a single line instead of writing using multiple lines of
if-else statements. It allows you to write clean and compact code.
For example, we can convert nested if-else statements into one line, as shown below.
If-else statement
score = 75
print('Fail')
else:
print('Merit')
else:
print('Distinction')
# Distinction
POWERED BY
# Distinction
POWERED BY
Final Thoughts
Mastering Python is crucial for anyone aiming to excel in technical interviews, whether they
are aspiring data professionals, developers, or software engineers. This guide has provided
an overview of common Python interview questions, ranging from basic to advanced levels,
as well as coding challenges and specific questions from top tech companies.
By practicing these questions and understanding their solutions, you can significantly
enhance your problem-solving skills and technical knowledge, making you well-prepared to
pass the technical and coding stages of your interviews.
Pursuing top Python certifications and engaging in continuous learning through courses and
projects will further bolster your expertise and career prospects in the tech industry. If you
need to brush up on your skills, be sure to complete our Associate Data Scientist in Python
career track.