Top 50 Python Interview Questions with Answers

Top 50 Python Interview Questions with Answers

With the increasing demand for Python developers, it becomes very important for the developer to ace the interview rounds in order to get selected. And for this, preparation for an interview is the very first step that matters the most. So, let’s get started with the top 50 Python Interview Questions.

So, in this blog, we are going to cover the most frequent, latest, and tricky python interview questions with their answers. This set covers beginner-level to advance level questions and will help you to clear your basic doubts and will help to brush up on your latest concepts.

(1) What is slicing in Python ?

Answer: Slicing is a method that helps us to get only a specific part of a string, list, or tuple. Slicing is widely used when making extracting and scrapping tools (eg. email extractor). It is also used very useful when there’s a large data in the file and we want a specific set of data from that file.

Suppose we only want the first word in the following string..

details = "CopyAssignments - One stop for projects needs"
print(details[:15])

(2) What are different scopes in Python ?

This is one of the favorite Python Interview Questions of interviewers.

Answer: The variables that we defined In Python are limited to the area of their definition. Suppose a variable is declared inside a function, now this variable cannot be used outside the function. This is known as scope.
Global scope: The variables that are created outside any function and are accessible anywhere in the code. This type of scope is known as the global scope.
Local scope: The variables that are declared inside any function and are accessible to only that particular function. This type of scope restricts the usage of the variable outside its declaration area. And this area is known as the local scope.

(3) What are the different modes that are available in Python ?

Answer: There are basically 2 different modes in Python and they are:
Interactive Mode: This mode is simply a command-line shell where we can only run small and simple line code. This mode is useful when we want to execute basic python commands. Creating and saving a file gets difficult when using this mode.
Script Mode: Whenever there’s a need of writing long programs, developing heavy software then this mode is used. This mode also lets the programmer save the code files in .py extension. Saving and creating files in this mode is way easier than Interactive Mode and thus increasing the accessibility. Many code editors are used such as VS Code, Atom, Sublime Text, etc.

(4) State the difference between Python List and Tuple ?

Answer: Python provides multiple data types including List and Tuple. They are basic data types that store data in sequence. The values that are stored in the list and tuples can be of any type. Let’s see where the difference lies:
List:
– This is represented in the form of [ ] (Square brackets)
– Memory usage is much more than a tuple
– Execution time is more
– Contents of the list can be edited that is they are mutable

Tuple:
– This is represented in the form of ( )
– Memory usage is very less than the list
– Execution time is less in the case of tuples
– Contents of a tuple cannot be edited and are thus known as immutable

(5) Explain Python Package Manager ?

Answer: Python Package Manager helps in organizing the different dependencies. It helps us to manage all the packages in a way that we can install new packages, remove and upgrade the existing ones. Dependency is a code that helps our code to perform properly. When working on large projects, there’s a new for a number of packages, and managing all of them gets quite difficult and that’s where PPM comes into the picture.

This question is also asked many times in Python Interviews.

(6) What do you mean by negative indices in Python ?

Answer: Whenever we want to search in list, tuple, or string from right, we use negative indices. It simply starts searching for the required element from the right i.e from the end.
Example:

details = "We are the Python Helpers"
print(details[-5])

(7) What are the different types of mutable and immutable data types in Python ?

Answer: Before classifying different data types, first let’s understand mutable and immutable.
Mutable: This simply means that the contents that are stored in this type of data type can be modified or changed. For example, in a list if we want to change the element at index 0 and replace it will some other element, then this is possible only when that data type is mutable.
Mutable data types: List, Set, and Dictionary

Immutable: Immutable means that the contents that are stored in this type of data type cannot be changed. For example, in a string, if we want to change any word, then it is not possible when that data type is immutable.
Immutable data types: Numbers, Tuples and Strings

(8) What is the significant use of [::-1] ?

Answer: Many times we simply want to reverse the contents of a list, tuple or string and for that, we use [::-1]. The syntax is [start, stop, count].
Example:

list = [100,"Python","Interview","Questions"]
print(list[::-1])

(9) Python is case sensitive or insensitive ?

Answer: Yes, Python is case sensitive and that simply means that it distinguishes between the letters that are written in the upper case from the letters that are written in the lower case.
Example:

var = "Hey there"
print(Var)

Error:

Traceback (most recent call last):
File “”, line 2, in
NameError: name ‘Var’ is not defined

Here, in the above code, we defined a variable named var and in the print statement we used Var and so we encountered a NameError.

(10) Explain the concept of try, raise and finally keywords ?

Answer: With exception-handling, we usually use these keywords. We place dangerous code in a try block that is the code that we want to try, use the raise statement to separately raise an error, and lastly insert code that we want to run in any case in the finally block.

(11) Whats are break, continue and pass statements ?

Answer: These statements are control statements that are defined in Python and are used to control the flow of the program. Suppose we want to terminate the loop or take an exit from the loop then in such cases these types of statements are used.
break: This statement simply terminates the loop and is used to take an exit from the loop. Any statement that is written after break statement won’t execute.
continue: This statement will bring the flow of the program back to the loop. Unlike break, it won’t exit from the loop but ignore all the remaining statements and take the flow back to the top of the loop.
pass: This statement supports a null operation which means that nothing will happen. Empty code is not allowed in case of loops, functions, etc and to avoid getting an error when an empty code is added, the pass is used.

(12) What is docstring and whats the need to add docstring ?

Answer: A docstring is a string that is added as the first statement in the definition of the object. docstring should not be very much descriptive. It helps to describe the functions, methods, classes etc. Docstring are written just after the function, method definition and in between “”” “”””
The first letter of docstring should be capital and it should end with a period(.)

Must do question, asked in most ot the python interviews.
Example:

def docfunction():
     """This is docstring inside a function."""
print(docfunction.__doc__)

(13) What will you randomize the content of list ?

Answer: There are multiple ways to shuffle the contents of the list but the easiest and most convenient way to do that is by importing a random library and using its function named as shuffle()
Example:

import random
List = ['We', 'Loves', 'To', 'Make', 'Projects', 'In', 'Python']
random.shuffle(List)
print(List)

(14) State the difference between del, remove() and pop() in Python ?

Answer: There’s a big difference between deleting, removing and popping an element. Let’s understand each in detail.
del:
– It is a keyword.
– Doesn’t return any value.
– It takes the index of the element that we want to delete.
– Either a single value or a whole list can be deleted using the del keyword.
Example:

mylist = [1, 2, 3, 2, 3, 4, 5]
del mylist[4]
print("After removal: ", mylist)

Output:

After removal: [1, 2, 3, 2, 4, 5]

remove():
– It is a method and not a keyword.
– As del, it doesn’t return any value.
– It takes the element that we want to remove as a parameter.
Example:

mylist = [1, 2, 3, 2, 3, 4, 5]
mylist.remove(4)
print("After removal: ", mylist)

Output:

After removal: [1, 2, 3, 2, 3, 5]

pop():
– It is a method.
– It does return the deleted value.
– Same as del, this also takes the index of the element.
Example:

mylist = [1, 2, 3, 2, 3, 4, 5]
mylist.pop(4)
print("After removal: ", mylist)

Output:

After removal: [1, 2, 3, 2, 4, 5]

(15) What’s the command to find out the current directory ?

Answer: in order to know which directory we are currently working in, at first, we need to import os module. The os module provides a number of functions that help in interacting with the system. The function that we will use is getcwd()
Example:

import os
os.getcwd()

The above command will return a path that shows the current directory.

(16) Explain the memory management in Python ? or What’s the roll of Python Memory Manager ? or How the memory is allocated in Python ?

Answer: Python is a programming language that uses the C programming language to implement it. Python’s memory allocations are managed by the Python memory management system. All Python objects and data structures are stored in a heap. The Python heap is managed by Python memory management. Object-specific allocators in the Python memory manager allow you to allocate memory for specific objects like ints, strings, and so on. Apart from that, the raw memory allocator connects with the operating system’s memory manager to guarantee that space on the private heap is available.

(17) What’s the efficient way to convert a list to string ?

Answer: To perform this we will use the join() method. It takes the objects that are in iterable form and joins them with a specific character.
Example:

alist = ["Converting", "List", "To", "String"]
astr = ' '.join(alist)
print(astr)

Output:

Converting List To String

(18) State the most unique way to remove a duplicate entry from list of elements ?

Answer: To remove an element in the list, as discussed above, we can use del keyword, pop() or remove() method. But what’s the most unique and tricky way to do this?

This python question is also good to know before attending the interview.
Example:

mylist=[102,202,101,202,45,103,2,45]
print(set(mylist))

Output:

{2, 101, 102, 103, 202, 45}

(19) State different types of membership operators available in Python ?

Answer: In Python, there are two membership operators namely in and not in. These operators are mainly used to verify whether an element is a member of that data type or not. Suppose we want to check if 2 is present in a particular set of numbers, then with the help of membership operators we can find that. These operators return values only in the form of true or false.

(20) Write a 3 liner code to print everything that is in the string except the whitespaces ?

Answer:

s = "This is CopyAssignments Python tutorial blog"
for i in s:
if i==' ': continue
print(i,end='')

(21) What do you mean by self in Python ?

Answer: Every class method, including init, takes a reference to the current instance of the class as its first argument. This argument is always referred to as self. Self refers to the freshly generated object in the init method, and the instance whose method was called in other class methods.

(22) What is type casting and what are some of the in-built functions that can be used for type casting ?

Answer: In simple language, the technique of converting a variable of one type to another is known as type casting. For typecasting, the built-in functions int(), float(), and str() should be used.

int() accepts a float or string literal as an argument and returns an int value.
float() accepts an int or string literal as an argument and returns a float value.
str() takes a float or int literal as an argument and returns a str type value.

(23) What’s the use of dir() function ?

Answer: The dir() function returns a list of any object’s properties and methods, such as modules, strings, dictionaries, functions and so on. This function returns all properties and methods, including built-in properties that are set by default for all objects in Python.
Example:

l = ["This", "Is","The",100,"Interview","Questions","Blog"]
result = dir(l)
print(result)

Output:

[‘add’, ‘class’, ‘contains’, ‘delattr’, ‘delitem’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘getitem’, ‘gt’, ‘hash’, ‘iadd’, ‘imul’, ‘init’, ‘init_subclass’, ‘iter’, ‘le’, ‘len’, ‘lt’, ‘mul’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘reversed’, ‘rmul’, ‘setattr’, ‘setitem’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

(24) What’s the alternate way for a peson who usually forgets to close file after opening ? or State the usage of with statement ?

Answer: A good practice in coding while using a file is that one should always close a file after opening it. This can be done using the close() method. But as an alternate way, we can also use the with statement. Whenever opening a file we should open it with a with statement.
Syntax: with open(“filename”, “mode”) as f_varaible:
Explanation:
filename: takes the name of the file
mode: the mode in which we want to access the file
f_variable: It is the file variable

You can also mark this question as important in you python interview questions list.

(25) Write a 2 liner code to display all the contents of the file in reverse order ?

Answer:

for l in reversed(list(open(name_of_file.txt))):
    print(l.rstrip())

(26) Explain how can we access or read a random line from the file ?

Answer:

import random
def readRandomLine(f):
    lines = open(f).read().splitlines()
    return random.choice(lines)
print(readRandomLine (‘CopyAssignemnts.txt’))

Explanation: Here, in the first line we imported a random library. Then we defined a function that opens a file in the reading method. The splitlines() splits the contents of the file in the form of lines. Now using the choice() method available in the random library, we accessed a random line.

(27) Explain file deletion in Python ?

Answer: To delete any file, at first we need to import os module and then we use the remove() method on the file that we want to delete.
Example:

import os
os.remove("name_of_file.txt")

(28) What’s the significant use of bytes() function ? or Explain bytes() function usage ?

Answer: The bytes() method returns non-modifiable bytes object that is initialized with the specified size and data. A bytes object is returned by the bytes() function. The distinction between bytes() and bytearray() is that bytes() returns a non-modifiable object, whereas bytearray() returns a modifiable object.
Example:

s = 'CopyAssignments for everything'
byteConversion = bytes(s, 'utf-8')
print(byteConversion)

Output:

b’CopyAssignments for everything’

(29) How will you open a file that is stored in C:\python.txt for append mode ?

Answer:

with open(“python.txt”, “a”) as f 

(30) *args and **kwargs in simple language ?

Answer: The main goal of defining a function in a Python programme is to run the code several times by passing different values to the function’s arguments. But sometimes what if we aren’t sure how many arguments we want to process each time we call that function? That’s where args and kwargs come into the picture.
*args: We can utilise a variable number of arguments as input to the function using the *args. Each time we call the function, the count of these numbers changes.
**kwargs: Many times, we need to send keyword arguments to a function, which are effectively key-value pairs. The function can take a configurable number of such keyword parameters. **kwargs are the moniker given to such arguments. The program receives such keyword parameters as a python dictionary containing a number of key-value pairs.

(31) What is PIL in Python, why it is used and command to install it?

Answer: PIL stands for Python Imaging Library and it is a fantastic image processing Python library. This library has a variety of functionality for working with photos in Python. Pillow and PIL (Python Imaging Library) are frequently confused, which is why we use “pip install Pillow” and not “pip install PIL” to instal PIL
Installation: pip install Pillow

(32) How will you free up memory in Python ?

Answer: Everything in Python is treated as an object. These objects are saved in memory and can be retrieved at any time. A lot of memory must first be allocated before the objects are to be stored in memory. The memory allocator in Python ensures that there is enough room to keep these objects. This is done by interacting with the operating system’s memory administrator. To avoid a memory shortage, we must clear the memory by deleting data or information from the software that is no longer needed. This can be done by forcing the Garbage Collector by using the following command.

import gc
gc.collect()

(33) What’s the main difference between range() and xrange() ?

Answer: Both the functions are used to generate a series of numbers. Both the functions takes 3 arguments and they are:

  • Start is the first vlaue that should be an integer and from that value our count will start. It’s default value is 0 and this paramater is optional.
  • Stop is the last integer value where we want our loop or count to stop. It is a compulsory parameter.
  • Step is a integral value that help us to choose the how the variable is to be incremented. It’s optional parameter and it’s default value is 1.

Syntax for range() : xrange(start,stop,step)
Syntax for xrange() : xrange(start,stop,step)

Difference:
range() :
– The list is generated by the range, which is a built-in function.
– Before starting the loop, it constructs a static list. That means that if we wrote range(1,101) it will create a list that can store up to 100 elements
– range() function is slower than xrange()

xrange() :
– This creates a sequence of objects and not a list. This sequence of objects is evaluated lazily on each iteration.
– xrange() is faster than range()

(34) Determine the output of this code:

def extendedList(val, list=[]):
    list.append(val)
    return list
l1 = extendedList(10)
l2 = extendedList(123,[])
l3 = extendedList('a')
l1,l2,l3

Output:
([10, ‘a’], [123], [10, ‘a’])
Explanation: 99% of the readers have guessed the output as : ([10],[123],[‘a’])
Unfortunately, that’s not the answer…But how?
This is because the list argument does not always start with its default value ([]) when we call the function. The function builds a new list when we declare it. The list is then used anytime we use it again without a list argument. This is because when we declare the function, not when we call it, it calculates the expressions in the default arguments. This question is also important for interveiws.

(35) Write a code to count the total number of uppercase letters in a particular file ?

Answer: Here, first we will open the file on which we want to perform this above operation and then apply the following logic:

count = 0
text = countletter.read()
for character in text:
    if character.isupper():
        count += 1

(36) What’s the use of abs() functions in Python ?

Answer: abs() is most widely used to get the absolute value of any number. Absolute values are always positive or zero and the absolute value of any negative number is equal to the positive of that number.

i1 = -1121
i2 = 80
f1 = -11.711
f2 = 1.987

print(abs(i1))
print(abs(i2))
print(abs(f1))
print(abs(f2))

Output:
1121
80
11.711
1.987

(37) Explain how can you access the values that are in an iterable obejct other than running a for loop?

Answer: The enumerate() function gives each item in an iterable object an index that can be used to find it later same as we access values of an array using an index. In Python, the enumerate() method is frequently used instead of for loop. This is because enumerate() can iterate over both the index and the item itself. Enumerate() also simplifies the code by requiring the programmer to write fewer lines.

(38) Identify the bug in this code that is written to remove the numbers that are less than 5 ?

num_list =[1,2,5,10,3,100,9,24]
for i in num_list:
    if i<5:
        num_list.remove(i)
print(num_list)

Incorrect Output: [2, 5, 10, 100, 9, 24]
Answer: Is each element in num_list smaller than 5? This code tests. If it is, that element is removed. 1 is actually smaller than 5 in the initial iteration. As a result, that item is removed from the list. However, this first iteration disturbs the indices of the list As a result, it tests element 5 but not element 2. We have two quick options for dealing with this scenario.

Method 1:

num_list = [1,2,5,10,3,100,9,24]
newnum_list = [i for i in num_list if i>=5]
print(newnum_list)

Method 2:

num_list = [1,2,5,10,3,100,9,24]
newnums_list = list(filter(lambda x:x>=5, num_list))
print(newnums_list)

Here in method 2, we used a built-in function filter() that will filter all the values that are less than 5 and will store the new values in a new list.

(39) State the use of a destructor ?

Answer: When an object is destroyed, destructors are called. It’s the exact opposite of a constructor. These methods are only invoked when the object is created and destroyed. They are not manually called but are totally automated. It has the ability to do a variety of tasks. When an object is deleted or destroyed, a destructor is called.

The following command is used to destroy an object: del obj

(40) What is ‘finalize’ in Python ?

Answer: Finalize is used to free up unmanaged resources and to assist in the cleanup process prior to Garbage Collection (GC). It’s usually in charge of memory management tasks.

(41) How will you take multi-liner input from user ?

Answer: Taking multi-liner input becomes very important when working on large projects. There are many ways to take multi-liner input, here’s the best way. We can use readlines() function from sys module. This question is also must for python interviews

import sys
msg = sys.stdin.readlines()
print(msg)

(42) Describe two ways in which you can create empty NumPy arrays ?

Answer: First of all let’s take a quick view at NumPy. Numpy is a Python package that makes it simple to work with multidimensional arrays. As Python by default does not provide any way to use array. NumPy provides a large number of functions that make working with arrays simple. Numpy has become an important aspect of Python when working with arrays, especially as the use of Python for data analytic and scientific tasks has grown.
Ways to create an empty array :

import numpy
numpy.array([])
import numpy
numpy.empty(shape=(0,0))

(43) What is eval() function and why should programmer avoid using it ?

Answer: eval is one of Python’s built-in functions. It evaluates the expressions after parsing the provided argument. Or, in another way, Python’s eval function evaluates the “string” as the expression and returns the output result as the “integer”.

Why should one avoid using it?
The eval function has been observed to begin deleting system files and corrupting the system’s environment. As a result, be cautious when using the eval() function to execute user input code. A programmer must ensure to examine the user-entered data first, and then proceed if everything appears to be in order.

(44) What will be the output of the following code ?

Answer:

print("Copy" + "Assignments"*2)

Output:
CopyAssignmentsAssignments
Explanation: As there are two strings in the print statement but the multiplication operator will first work on the Assignments string and then concatenate that string AssignmentsAssignments with Copy string.

(45) When to use append() and extend() ? or Differentiate between append() and extened() ?

Answer: The main differentiator between append() and extend() method is that append() simply adds the content to the end of the list while extend() on the other hand is used to add a list of elements at the end. Let’s understand with an example:
append():

list1 = [100,200,300]
list2 = [500,600,700,800]
list1.append(400)
print(list1)

extend():

list1 = [100,200,300]
list2 = [500,600,700,800]
list1.append(list2)
print(list1)

(46) Convert an interger to Unicode (only using built-in function) ?

Answer: To perform this, we will use Python’s built-in function named chr(). This takes an integer value as a single parameter. Here, one to take note of is that it only accepts integer arguments.

print(chr(100))
print(chr(99))
print(chr(98))
print(chr(97))

Output:
d
c
b
a

(47) Guess the output for the following Python code ?

list = ['ab', 'bc', 'cd', 'de', 'ef']
print list[10:]

Output:
[]

Explanation: The code above will print [] and will not throw an IndexError. Whenever we attempt to access a member of the list with an index that exceeds the number of members (e.g., accessing list[10] in the list above) and results in an IndexError, as we might assume. But that’s not the case. If we try to access a slice of a list at a starting index that is greater than the number of members in the list, we will not get an IndexError but instead, the code will return an empty list.

(48) Consider the following code and state the output ?

list = [ [ ] ] * 6
print(list) 
list[0].append(99)
print(list)
list[1].append(98)
print(list)
list.append(97)
print(list)

Output:
[[], [], [], [], [], []]
[[99], [99], [99], [99], [99], [99]]
[[99, 98], [99, 98], [99, 98], [99, 98], [99, 98], [99, 98]]
[[99, 98], [99, 98], [99, 98], [99, 98], [99, 98], [99, 98], 97]

Explanation: The first line of output is obvious and straightforward; that the above code list = [[]] * 6 will print a list of six lists. The output of the first line will look like: [[], [], [], [], [], []].
The important point to note here is that list = [[]] * 6 does not construct a list with six unique lists; instead of that, it creates a list with six references to the same list. Now, let us understand other lines of the cod

list[0].append(99) – append(99) adds 99 to the beginning of the list. However, because all six lists relate to the same list, the result is:[[99], [99], [99], [99], [99], [99]]

list[1].append(98) – append(98) is a function that adds 98 to the second list. However, because all six lists relate to the same list, the result is now: [[99, 98], [99, 98], [99, 98], [99, 98], [99, 98], [99, 98]]

list.append(97), on the other hand, adds a completely new member to the “outer” list and line must have tricked you as well. It will produce a result that will look like: [[99, 98], [99, 98], [99, 98], [99, 98], [99, 98], [99, 98], 97].

(49) Suppose you have a CSV file and you want to read the contents of that file in the form of array with a seperator , ?

Answer:

from numpy import genfromtxt
csv_to_array = genfromtxt('sampleFile.csv', delimiter=',')

Explanation: For this purpose, we will use the NumPy package. We imported genfromtxt() function to show the CSV file content in the form of an array. genfromtxt takes in multiple parameters. Most of them are optional and can be used according to the need. Here, in the above solution, we have only given 2 parameters that are the file name and the delimiter (separator).

(50) What if the plus operator doesn’t exist then how will you add two given integers that are greater than zero ? or Add two integers in less than 10 lines of code but without the use of plus operator ?

Answer:

def add_two_int(n1, n2):
   while n2 != 0:
       data = n1 & n2
       n1 = n1 ^ n2
       n2 = data << 1
   return n1
print(add_two_int(120, 19))

Explanation: First of all, we defined a function add_two_int that takes in two parameters n1 and n1 (integer values only). Inside the function, we used a while loop with a condition that the parameters should not be equal to zero.
The next three lines are the logic to perform addition without the use of the plus operator.
Bitwise & will perform the AND operation between the numbers. This operator return 1 only if both the bits are 1 otherwise it returns 0. data = n1 & n2 will give 16 as output.
Bitwise ^ will perform the XOR operation and it returns 1 when one bit is 1 and the other is 0.
n1 = n1 ^ n2 will add 107 to the variable n1.
Bitwise << is a left shift operator and its function is to move the bits to the left and it fills the empty spaces with 0. n2 = data << 1 this will set the value of n2 to 32.

The above will continue until the value of n2 becomes 0 and then the loop will terminate and will return n1.

Here’s the end of this post. We hope these hand-picked interview questions will help you clear your doubts and will make you interview-ready.


Also Read:




Share:

Author: Ayush Purawr