Welcome to the first step of preparing for your Data Science job interview. Here’s a comprehensive and extensive list of Python interview 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.
In this article, you will get insights into essential Python coding interview questions and effective strategies to tackle common Python coding questions. We’ll also provide valuable Python interview questions and answers to help you prepare thoroughly for your next interview.
Ans. We can convert a given string to an integer using a built-in function int(). e.g.-
a = ‘5’ print(int(a))
Variable ‘a’ is a string that is now converted to an integer, as shown below:
Output:
5
Ans. Below is the code to convert a string to a list in Python.
str1 = "Analytics Vidhya"
print(str1.split(" "))
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’]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)
print("The reversed string is: ", str2)
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:
my_list = [3, 2, 1]
my_list.sort()
print(my_list)
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:
Given a list [1, 2, 3, 4].
The indexing of the list starts from 0.
The first element of the list can be accessed using list[0], which will print element “1”.
The second element can be accessed using list[1] and so on.
Ans. There are two ways in which we can delete elements from the list:
1. By using the remove() function
The remove () function deletes the mentioned element from the list.
list1 = [1, 2, 3, 4]
list1.remove(2)
print(list1)
Output:
[1, 3, 4]2. By using the pop() function
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:
list1 = [1, 2, 3, 4]
list1.clear()
It will delete the entire list.
Ans. The two ways of reversing an array are as follows:
1. Using the flip() function
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.flip(arr1)
print(arr2)
Output:
[4, 3, 2, 1]2. Without using any function
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = arr1[::-1]
print(arr2)
Output:
[4,3,2,1]Ans. Access: We can access an element of an array by using array_name[index].
print(arr[index])
Delete: We can delete the element of an array using the delete() function.
import numpy as np
arr2 = [1, 2, 3, 4]
x = np.delete(arr2, 0)
print(x)
Output:
[2,3,4]Update: We can update the element of an array using the below syntax:
array_name[index] = element
Ans. Suppose, given two lists are:
List1= [“W”, “a”, “w”,”b”]
List2 = [“e”, “ “,”riting”,”log”]
And the output should be:
[‘We’, ‘a ‘, ‘writing’, ‘blog’]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:
[‘We’, ‘a ‘, ‘writing’, ‘blog’]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.
lst = [1, 2, 3, 4]
lst_final = []
for x in lst:
lst_final.append(x * x)
print(lst_final)
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]
Output: [1, 4, 9, 16]
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 notably faster than Python lists for numerical operations. NumPy is an open-source library designed for efficient array operations in Python, leveraging optimized implementations in C. Unlike Python lists, which are interpreted, NumPy arrays are executed in a compiled language, enhancing their performance significantly.
Python also includes a built-in array
module for basic operations, which can be imported using 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.
In general, tuples are faster than lists in Python.
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.
Here are some key properties of sets in Python:
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.
a = 'This is a string'
li = a.split(' ')
print(li)
Output: [‘This’, ‘is’, ‘a’, ‘string’]
The join() method is a built-in function of Python’s str class that concatenates a list of strings into a single string. It is called on a delimiter string and invoked with a list of strings to be joined. The delimiter string is inserted between each string in the list when the strings are concatenated.
Here is an example of how to use the join() method:
“ “.join(li)
Output: This is a string
Here the list is joined with a space in between.
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.
Ans. Here are the top 5 Python string functions:
s = 'Hello, World!'
print(len(s))
13
s = ' Hello, World! '
print(s.strip())
'Hello, World!'
s = 'Hello, World!'
print(s.replace('World', 'Universe'))
'Hello, Universe!'
s = 'Hello, World!'
print(s.split(','))
['Hello', ' World!']
s = 'Hello, World!'
print(s.upper())
'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.
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.
Functions can also help in code optimization:
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)
Output: This will print 5 and then 10
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.
Ans. Return is used to exit a function and return a value to the caller. When a return statement is encountered, the function terminates immediately, and the value of the expression following the return statement is returned to the caller.
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.
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().
Here’s an example of a lambda function in Python:
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.
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. Docstring is the short form for documentation string. It is a type of string used to document how a function or a class works, its various input parameters, and any examples for the usage of the function or class. It is enclosed by triple quotes(“”” “””). A well-written docstring helps people to understand the usage of the function or class.
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.
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. Here are the various ways of adding elements to a list:
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
Ans. It has a time complexity of O(sqrt(n)). We can do it faster with the sieve of Eratosthenes.
Ans. One way is by using a third variable
temp = a
a = b
b = temp
In Python, we can also do it without using the third variable
a, b = b, a
Ans.
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
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().
Ans.
from functools import reduce
reduce(lambda x, y: x if x < y else y, b)
This will give the minimum value in the list.
Ans.
‘,’.join(list)
Ans.
[i for i in range(n) if i%2 != 0]
Ans. ‘Remove’ removes the first occurrence of a given element. ‘Del’ removes elements based on the given index.
Ans.
dict_[min(dict_.keys(), key=(lambda k: dict_[k]))
Ans.
def mean_tuple(numbers):
result = [sum(x) / len(x) for x in zip(*numbers)]
return result
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:
Ans: The 3 different types of methods in Python OOP are:
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. array[:, 0] returns 1 st column as 1D array.
array[:, [0]] returns 1st columns as multi-dimensional array.
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.
Ans. We can use concatenate method.
import numpy as np
a = np.array([[10, 4], [8, 12]])
b = np.array([[15, 6]])
c = np.concatenate((a, b), axis=0)
The result will be
[[10, 4]
[8, 12]
[15, 6]]
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.
np.where((arr[1:-1] > arr[0:-2]) * (arr[1:-1] > arr[2:]))[0] + 1
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.
Ans.
resulted_arr = np.char.join(",", array)
Ans. We can use the pad method of numpy.
New_arr = np.pad(existing_arr, pad_width=1, mode='constant',
constant_values=1)
Ans. We can use the swapaxes method.
np.swapaxes(arr,0,1)
Ans. argsort() method returns indices that can sort the array.
array.argsort( ) [ -N: ][: : -1]
This gives the indices of n maximum values.
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'])
Ans. We can use idmax method for that.
df[‘column’].idxmax()
This returns the row index with the maximum value of the column specified.
Ans.
df[‘column’].str.split(pat=” ”, expand=True)
Here we can specify the pattern by which to split the column with the pat argument.
Ans. While they can be used for elementwise operations, map() is used for series, while applymap() is used for dataframes.
Ans. We can use the tilde(~) operator to convert True values to False and vice versa.
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)
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.
Ans. We can use numpy.unique(list, return_counts=True)
This will return values and their counts in two arrays.
Ans. Indexing creates an index, whereas slicing makes a shallow copy. Different types of indexing are possible, but there is no slicing category.
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. We have cover everything in this article of Python interview Questions.
Hope you like the article! Python coding interview questions often focus on basic topics like syntax, data structures, and algorithms. Knowing common Python coding questions can really help you do well in interviews. Practicing Python interview questions and answers is a great way to get ready for technical tests. Understanding these Python interview questions will make you feel more confident and improve your problem-solving skills during the interview.
You can go through the following articles to learn and practice python topics for your next Python interview Questions or upcoming python viva:
Cannot read most as it ask you to log in. I am logged in.
Question 5: Mutable objects: They can be updated when required. eg- tuples Immutable objects: They can’t be updated once defined. eg- list
There is an error in question 5 : Mutable : They can be updated, eg : lists Immutable : They cant be updated, eg : tuples