90 Python Interview Questions and Answers (2024 Edition)
90 Python Interview Questions and Answers (2024 Edition)
Introduction
Welcome to the first step of preparing for your Data Science job interview. Here’s a comprehensive and
extensive list of Python questions and answers to help you ace that interview and get your dream job!
Python is an interpreted and general-purpose programming language in high demand nowadays due to its
usage in Artificial Intelligence(AI). Therefore, it becomes indispensable for every Data Science aspirant to
have a strong understanding of functions used in Python. As you delve into mastering Python for your
upcoming interview, these Python interview questions will surely guide you towards success.
This article covers some important and frequently asked Python coding interview questions and Python
programming interview questions to help Data Science aspirants get a good grasp of the topic.
Ans. We can convert a given string to an integer using a built-in function int(). e.g.-
a = ‘5’ print(int(a))
Output:
The split() function separates the given string by the defined delimiter, i.e., space(” “) here. Therefore,
Analytics and Vidhya break down into two strings in a list.
Output:
[‘Analytics’, ‘Vidhya’]
Q3. Write a code snippet to reverse a string.
Ans. Here, we have reversed a string without using any in-built function.
str1 = "Analytics Vidhya" str2 = "" for i in str1: str2 = i + str2 print("The original string is: ", str1)
The above code picks the first letter, i.e., ‘A’, then adds ‘n’ at the beginning.
Further, ‘nA’ is taken as str2, ‘ a’ is added before it, and so on.
Then ‘anA’ becomes str2, and the next letter, i.e., ‘l’, is appended at the start of str2 to make it ‘lanA.’
This is how the above code works to reverse the string.
Output:
ayhdiV scitylanA
Ans. We can sort a list in Python using the sort() function. The following code will illustrate this:
The above code sort the list using the sort() function.
Output:
[1, 2, 3]
Ans. Mutable objects: They can be updated once defined. e.g., list.
Immutable objects: They cannot be updated. e.g., tuples.
Ans. We can delete the file in Python using the os module. The remove() function of the os module is used
to delete a file in Python by passing the filename as a parameter. e.g.
import os os.remove("txt1.txt")
Ans. The element in a list can be accessed using list_name [index]. For instance:
The first element of the list can be accessed using list[0], which will print element “1”.
Ans. There are two ways in which we can delete elements from the list:
The remove () function deletes the mentioned element from the list.
Output:
[1, 3, 4]
Pop() function delete element mentioned at a specific index from the list
list1.pop(1) print(list1)
Output:
[1, 4]
Ans. We can delete a list in Python using the clear() function. The following code will illustrate this:
Output:
[4, 3, 2, 1]
2. Without using any function
Output:
[4,3,2,1]
Q11. Write a code snippet to get an element, delete an element, and update an
element in an array.
print(arr[index])
Delete: We can delete the element of an array using the delete() function.
Output:
[2,3,4]
Update: We can update the element of an array using the below syntax:
array_name[index] = element
This can concatenate the two lists using the zip() function, which iterates through both lists and combines
them index-wise.
lst1 = ['W', 'a', 'w', 'b'] lst2 = ['e', ' ', 'riting', 'log'] lst3 = [x + y for x, y in zip(lst1, lst2)]
print(lst3)
Output:
Q13. Write a code snippet to generate the square of every element of a list.
Ans. First, create an empty list. We used a for loop to iterate through every element of a list and multiply
the element by itself to generate a square of it. Then, append it to the newly generated list.
The for loop takes the first element, i.e., 1, multiply it with itself, and then appends it to the list. It then
takes the second element, i.e., 2, multiplies it by itself, appends it to the list, and so on.
Input: [1, 2, 3, 4]
Ans. In Python 2, range() returns a list, and xrange() returns an iterator. But in Python 3 xrange() no longer
exists while range() returns an iterator.
Ans. Pickling is converting a Python object (list, dict, function, etc.) to a byte stream(0s and 1s), and
unpickling is converting the byte stream back to a python object. It is used to transfer and store various
Python objects. We can use pickle or dill Python packages for this.
Ans. __init__ method is used in Python to initialize the attributes of the object when the object is created.
So, it is similar to the constructor in Java or C++. It is declared within the class as a reserved method.
Ans. It is the recommended coding conventions guide to follow for easier readability of the code. Since
Multiple people work on the same project, it is preferable to follow a similar style for better readability and
consistency. However, we can use our judgment about what style to follow, If there is any need to deviate
from conventions.
Ans. NumPy arrays are faster than Python lists for numerical operations.
NumPy is an open-source library for working with arrays in Python, and it provides a number of functions
for performing operations on arrays efficiently.
NumPy arrays outpace Python lists due to their implementation in C, whereas Python lists are implemented
in Python. This signifies that operations on NumPy arrays occur in a compiled language, rendering them
quicker than operations on Python lists, which occur in an interpreted language
Python also has an inbuilt array library for basic operations. W can use it as ‘import array as arr’
Ans. In Python, a list is an ordered collection of objects that can be of different types. Lists are mutable,
which means that you can change the value of a list element or add or remove elements from a list. Lists
are created using square brackets and a comma-separated list of values.
A tuple is also an ordered collection of objects, but it is immutable, which means that you cannot change
the value of a tuple element or add or remove elements from a tuple.
Lists are defined using square brackets ([ ‘’ ]), while tuples are defined using parentheses ((‘’, )).
Lists have several built-in methods for adding, removing, and manipulating elements, while tuples do not
have these methods.
Q20. What are Python sets? Explain some of the properties of sets.
Ans. In Python, a set is an unordered collection of unique objects. Sets are often used to store a collection
of distinct objects and to perform membership tests (i.e., to check if an object is in the set). Sets are
defined using curly braces ({ and }) and a comma-separated list of values.
Sets are unordered: Sets do not have a specific order, so you cannot index or slice them like you can
with lists or tuples.
Sets are unique: Sets only allow unique objects, so if you try to add a duplicate object to a set, it will
not be added.
Sets are mutable: You can add or remove elements from a set using the add and remove methods.
Sets are not indexed: Sets do not support indexing or slicing, so you cannot access individual elements
of a set using an index.
Sets are not hashable: Sets are mutable, so they cannot be used as keys in dictionaries or as elements
in other sets. If you need to use a mutable object as a key or an element in a set, you can use a tuple or
a frozen set (an immutable version of a set).
Ans. Split and join are both functions of Python strings, but they are completely different when it comes to
functioning.
The split function is used to create a list from strings based on some delimiter, for e.g., space.
“ “.join(li)
Ans. In Python, the logical operations and, or, and not can be used to perform boolean operations on truth
values (True and False).
The and operator returns True if both the operands are True, and False otherwise.
The or operator returns True if either of the operands is True, and False if both operands are False.
The not operator inverts the boolean value of its operand. If the operand is True, not return False, and if the
operand is False, not return True.
13
strip(): This function removes leading and trailing whitespace from a string.
‘Hello, World!’
replace(): This function replaces all occurrences of a specified string with another string.
‘Hello, Universe!’
split(): This function splits a string into a list of substrings based on a delimiter.
upper() and lower(): These functions convert a string to uppercase or lowercase, respectively.
‘HELLO, WORLD!’
s.lower()
‘hello, world!’
In addition to them, string also has capitalize, isalnum, isalpha, and other methods.
Ans. Pass is a null statement that does nothing. It is often used as a placeholder where a statement is
required syntactically, but no action needs to be taken. For example, if you want to define a function or a
class but haven’t yet decided what it should do, you can use the pass as a placeholder.
Ans. Continue is used in a loop to skip over the current iteration and move on to the next one. When
continue is encountered, the current iteration of the loop is terminated, and the next one begins.
Ans. In Python, an immutable object is an object whose state cannot be modified after it is created. This
means that you can’t change the value of an immutable object once it is created. Examples of immutable
objects in Python include numbers (such as integers, floats, and complex numbers), strings, and tuples.
On the other hand, a mutable object is an object whose state can be modified after it is created. This
means that you can change the value of a mutable object after it is created. Examples of mutable objects in
Python include lists and dictionaries.
Understanding the difference between immutable and mutable objects in Python is important because it
can affect how you use and manipulate data in your code. For example, if you have a list of numbers and
you want to sort the list in ascending order, you can use the built-in sort() method to do this. However, if
you have a tuple of numbers, you can’t use the sort() method because tuples are immutable. Instead, you
would have to create a new sorted tuple from the original tuple.
Ans. The try and except blocks in Python are used to handle exceptions. An exception is an error that
occurs during the execution of a program.
The try block contains code that might cause an exception to be raised. The except block contains code
that is executed if an exception is raised during the execution of the try block.
Using a try-except block will save the code from an error to occur and can be executed with a message or
output we want in the except block.
Ans. 2 mutable data types are Dictionary and List. You can change/edit the values in a Python dictionary
and a list. It is not necessary to make a new list which means that it satisfies the property of mutability.
2 immutable data types are Tuples and String. You cannot edit a string or a value in a tuple once it is
created. You need to either assign the values to the tuple or make a new tuple.
Q29. What are Python functions, and how do they help in code optimization?
Ans. In Python, a function is a block of code that can be called by other parts of your program. Functions
are useful because they allow you to reuse code and divide your code into logical blocks that can be tested
and maintained separately.
To call a function in Python, you simply use the function name followed by a pair of parentheses and any
necessary arguments. The function may or may not return a value that depends on the usage of the turn
statement.
Code reuse: Functions allow you to reuse code by encapsulating it in a single place and calling it
multiple times from different parts of your program. This can help to reduce redundancy and make your
code more concise and easier to maintain.
Improved readability: By dividing your code into logical blocks, functions can make your code more
readable and easier to understand. This can make it easier to identify bugs and make changes to your
code.
Easier testing: Functions allow you to test individual blocks of code separately, which can make it
easier to find and fix bugs.
Improved performance: Functions can also help to improve the performance of your code by allowing
you to use optimized code libraries or by allowing the Python interpreter to optimize the code more
effectively.
Q30. Why does NumPy have huge popularity in the field of data science?
Ans. NumPy (short for Numerical Python) is a popular library for scientific computing in Python. It has
gained a lot of popularity in the data science community because it provides fast and efficient tools for
working with large arrays and matrices of numeric data.
NumPy provides fast and efficient operations on arrays and matrices of numerical data. It uses optimized C
and Fortran code behind the scenes to perform these operations, which makes them much faster than
equivalent operations using Python’s built-in data structures. It provides fast and efficient tools for
working with large arrays and matrices of numeric data.
NumPy provides a large number of functions for performing mathematical and statistical operations on
arrays and matrices.
It allows you to work with large amounts of data efficiently. It provides tools for handling large datasets
that would not fit in memory, such as functions for reading and writing data to disk and for loading only a
portion of a dataset into memory at a time.
NumPy integrates well with other scientific computing libraries in Python, such as SciPy (Scientific Python)
and pandas. This makes it easy to use NumPy with other Python libraries to perform more complex data
science tasks.
Ans. List comprehension and dict comprehension are both concise ways to create new lists or dictionaries
from existing iterables.
List comprehension is a concise way to create a list. It consists of square brackets containing an
expression followed by a for clause, then zero or more for or if clauses. The result is a new list that
evaluates the expression in the context of the for and if clauses.
Dict comprehension is a concise way to create a dictionary. It consists of curly braces containing a key-
value pair, followed by a for clause, then zero or more for or if clauses. A result is a new dictionary that
evaluates the key-value pair in the context of the for and if clauses.
Ans. In Python, a variable that is defined outside of any function or class is a global variable, while a
variable that is defined inside a function or class is a local variable.
A global variable can be accessed from anywhere in the program, including inside functions and classes.
However, a local variable can only be accessed within the function or class in which it is defined.
It is important to note that you can use the same name for a global variable and a local variable, but the
local variable will take precedence over the global variable within the function or class in which it is
defined.
# This is a global variable x = 10 def func(): # This is a local variable x = 5 print(x) func() print(x)
In the example above, the x variable inside the func() function is a local variable, so it takes precedence
over the global variable x. Therefore, when x is printed inside the function, it prints 5; when it is printed
outside the function, it prints 10.
Ans. An ordered dictionary, also known as an OrderedDict, is a subclass of the built-in Python dictionary
class that maintains the order of elements in which they were added. In a regular dictionary, the order of
elements is determined by the hash values of their keys, which can change over time as the dictionary
grows and evolves. An ordered dictionary, on the other hand, uses a doubly linked list to remember the
order of elements, so that the order of elements is preserved regardless of how the dictionary changes.
Yield, on the other hand, is used to define a generator function. A generator function is a special kind of
function that produces a sequence of values one at a time instead of returning a single value. When a yield
statement is encountered, the generator function produces a value and suspends its execution, saving its
state for later.
Q35. What are lambda functions in Python, and why are they important?
Ans. Python supports the lambda function, which is a small anonymous function. You can use lambda
functions when you don’t want to define a function using the def keyword.
Lambda functions are useful when you need a small function for a short period of time. They are often
used in combination with higher-order functions, such as map(), filter(), and reduce().
a = lambda x: x + 10 a(5)
15
In this example, the lambda function takes one argument (x) and adds 10 to it. The lambda function returns
the result of this operation when it is called.
Lambda functions are important because they allow you to create small anonymous functions in a concise
way. They are often used in functional programming, a programming paradigm that emphasizes using
functions to solve problems.
Ans. In Python, the assert statement is used to test a condition. If the condition is True, then the program
continues to execute. If the condition is False, then the program raises an AssertionError exception.
The assert statement is often used to check the internal consistency of a program. For example, you might
use an assert statement to check that a list is sorted before performing a binary search on the list.
It’s important to note that the assert statement is used for debugging purposes and is not intended to be
used as a way to handle runtime errors. In production code, you should use try and except blocks to handle
exceptions that might be raised at runtime.
Ans. In Python, decorators are a way to modify or extend the functionality of a function, method, or class
without changing their source code. Decorators are typically implemented as functions that take another
function as an argument and return a new function that has the desired behavior.
We can use the decorator function by adding it just before the function we are applying using
@decorator_function syntax.
Ans. The 5 built-in data types in Python are: None Type, Numeric Types (int, float, complex, bool), Sequence
Types (list, tuple, range, str), Map Type (dictionary), and Set types (set, frozenset).
Ans. A frozenset is an immutable variant of a set, like how a tuple is an immutable variant list.
Ans. We can use tuples as dictionary keys as they are hashable. Since tuples are immutable, it is safer to
use if we don’t want values to change. Tuples are faster and have less memory, so we can use tuples to
access only the elements.
Q41. Is removing the first item or last item takes the same time in the Python list?
Ans. No, removing the last item is O(1), while removing the first item is O(n)
Ans. We can use a deque from the collections module, which is implemented as a doubly linked list, to
remove elements faster at any index.
Ans. Python sequence data types can be accessed with both positive and negative numbers. With negative
indexing, -1 refers to the last element, -2 refers to the penultimate element, and so on.
Ans. While representing floating point numbers like 2.5 is easier in the decimal system, representing the
same in a binary system needs a lot of bits of information. Since the number of bits is limited, there can be
rounding errors in floating-point calculations.
Ans. args and *kwargs are syntax used for denoting variable length arguments and variable length keyword
arguments, respectively. Here and * represents the syntax, while the args and kwargs are words used by
convention. We can also use other words.
Ans. A generator in Python returns an iterator that produces sequences of values one at a time. We use the
yield keyword to produce values.
Ans. Since the generator doesn’t produce all the values at the same time, it saves memory if we use the
generator to process the sequence of values without the need to save the initial values.
Q49. How can we iterate through multiple lists at the same time?
Ans. We can use zip() function to aggregate multiple lists and return an iterator of tuples where each tuple
contains elements of different lists of the same index.
Ans.
from math import sqrt def prime_or_not(number): for i in range(2, int(sqrt(number)) + 1): if number % i == 0:
return 0 return 1
Q52. What is the time complexity of the above program, and is there a faster way to do
it?
Ans. It has a time complexity of O(sqrt(n)). We can do it faster with the sieve of Eratosthenes.
Q53. What are the ways to swap the values of two elements?
temp = a a = b b = temp
a, b = b, a
Q54. Write a program in Python to return the factorial of a given number using
recursion.
Ans.
Ans. We can use the divide and conquer algorithm technique to calculate faster. It is implemented in a
built-in math library with math.factorial().
Q56. How do you find the minimum value in a list with a lambda function?
Ans.
Ans.
‘,’.join(list)
Q58. Write a code to select only odd numbers using list comprehension.
Ans.
Ans. ‘Remove’ removes the first occurrence of a given element. ‘Del’ removes elements based on the given
index.
Ans.
Ans.
Ans. Self is used to represent the instance of the class. With this, we can access the attributes and
methods of the class with an object. It binds the attributes of the object with the given arguments. Self is
not a keyword. We can also use any other non-keyword though it is better to follow convention.
Ans: The 3 different types of variables in Python OOP (object-oriented programming) are:
1. Class variables: They are defined inside the class but outside other methods and are available to
access for any instance of the class.
2. Instance variables: They are defined for each instance of the class separately and accessible by that
instance of the class.
3. Local variables: They are defined inside the method and accessible only inside that method.
1. Class methods: They can access only class variables and are used to modify the class state.
2. Instance methods: They can access both class and instance variables and are used to modify the
object (instance of a class) state.
3. Static methods: They can’t access either class or instance variables and can be used for functions that
are suitable to be in class without accessing class or instance variables.
Ans. With inheritance, we can use the attributes and methods of the parent class in the child class. We can
also modify the parent class methods to suit the child class.
Ans. We can use (underscore) or _(double underscore) to denote protected and private variables. They can
be used to restrict access to the attributes of the class.
Ans. We can use the size method of the array to check whether it returns 0. Then it means the array can
contain only zeros.
import numpy as np a = np.array([[10, 4], [8, 12]]) b = np.array([[15, 6]]) c = np.concatenate((a, b),
axis=0)
Also you can Watch the Video for Python Interview Questions and Answers
Python Interview Question…
Question…
Ans. A local maxima is a point greater than both of its neighbors from either side. In a given array, the
following code can produce local maxima points.
Ans. The split() function is used to split an array in n number of equal parts. If it is not possible to split it
into an equal number of parts, split() raises an error. On the other hand, array_split() splits an array into n
unequal parts.
Q72. Write code to insert commas between characters of all elements in an array.
Ans.
np.swapaxes(arr,0,1)
Ans. argsort() method returns indices that can sort the array.
Ans. When a variable takes a limited number of possible values, we can use category datatype for that
variable which is internally represented with numbers, so faster to process.
Ans.
df["column"] = df["column"].astype(int)
Ans. loc() is used to access the rows or columns using labels, while iloc() is used to access using position-
based indexing.
Ans.
df.sort_values(by=['col1', 'col2'])
Q80. Find the row which has the maximum value of a given column.
df[‘column’].idxmax()
This returns the row index with the maximum value of the column specified.
Q81. How can you split a column which contains strings into multiple columns?
Ans.
df[‘column’].str.split(pat=” ”, expand=True)
Here we can specify the pattern by which to split the column with the pat argument.
Q83. How can we convert the True values of a query to False and vice-versa?
Ans. We can use the tilde(~) operator to convert True values to False and vice versa.
Q84. How can we find a change in percentage from one row to another?
Ans. We can use the following code to find the percentage change between the previous row to the current
row.
df.pct_change(periods=1)
Q85. How can we find the coefficient of variance for data frame columns?
Ans. Since coefficient of variance is standard deviation divided by mean, we can use df.std()/df.mean()
Ans. We can use the .lstrip() method to remove the leading whitespace for a string.
Ans. enumerate() in Python iterates a sequence and returns the index position and its corresponding value.
Ans. Deepcopy copies the contents of the object to another location. Changes made in one object do not
affect the other. In shallow copy, only the reference is copied. So, changes made in one affect the other
object.
Ans. An object which can invoke a process is a callable object. It uses the call method. Functions are
examples of that. Callable objects have () at the end, while non-callable methods don’t have () at the end.
Q90. How can we find unique elements and value counts of a list using Numpy?
Ans. Indexing creates an index, whereas slicing makes a shallow copy. Different types of indexing are
possible, but there is no slicing category.
Conclusion
Phew! We’ve finally reached the end of this very comprehensive article. Hope these Python interview
questions and answers have been beneficial to you. I’m sure you’ve all learned a few things from this and
are now confident about your next interview. These Python coding Interview questions also act as Python
tutorials for freshers and intermediate-level programmers and cover functions that most Python developers
frequently use.
Reading List
You can go through the following articles to learn and practice python topics:
Saumyab271