Python Interview Questions

By | May 20, 2020
Python Interview Questions

Python is one of the most versatile and powerful programming languages. It has a very bright future and promises many opportunities for its developer. So, whenever you apply for a job as a Python Developer, you have to face the interview where the interviewer will test your python skills. It has often seen that during interview interviewer ask questions from core python and candidate not able to answer those. So it always recommended that make your basics concepts reliable. Here in this article, we have provided Top 100 Python questions, which are frequently asked during python Interviews. We hope these Python Interview questions and answers would help you to crack the interview.

Best Python Interview Questions

Question: Who is the creator of Python?
Answer: Guido van Rossum


Question: What is Python?
Answer: Python is the most popular, high-level, object-oriented, interpreted programming language.

Question: What do you mean by interpreted programming language?
Answer: An interpreted programming language in which the code gets directly executed without compilation.

Question: Tell some benefits of Python.

  • It is Dynamic language
  • It supports object-oriented programming languages
  • It does not have a concept of access modifiers like private, public, and protected but you can use magic functions to use the methods as public or private.
  • It has a very simple syntax which makes it easy to learn.
  • Apart from desktop application python is also used for web development.

Question: What is a Dynamic type Language?
Answer: Unlike other programming languages in python for every variable, you do not need to declare its data type. That makes Python a Dynamic language.

E.g. var1=10 # var1 is an integer type
var2 =“Hello world” # var2 is a string

Question: Name the tool in python which is used to find Bugs
Answer: PyChecker and Pylint.

Question: What pass keyword do and why do you use it?
Answer: The pass is a special keyword in the python which performs the NULL operation when you execute a pass keyword nothing happens.

In python, if you declare an if statement or a function you have to define the function and the statement if you do not define them the python interpreter through an error. To overcome this error, you can use the pass keyword inside the if statements and functions.


remove_h=”hello world”
for i in remove_h:
    if i==h:



Question: Write code to get the current file directory.

import os


Question: Name all the inbuild datatype in python:
Answer: Python has 6 inbuilt data types

  1. Numbers
  2. Strings
  3. List
  4. Tuples
  5. Dictionaries
  6. Sets

Question: What are Mutable and Immutable Datatypes

  • Mutable are those data types in python whose value can be changed. E.g. list, Dictionaries, and Sets
  • Immutable are those data types once they have been assigned you cannot manipulate their values. E.g. Strings, Tuples and Numbers

Question: Comment on Python Memory management.
Answer: Python interpreter handles memory management. It uses private heaps to control and maintain a memory. In python the user does not get any access related to its memory management, python memory management takes control of all the memory action by itself. Python has an automatic garbage collector.

Question: Write a code to convert 144 into a string


Question: What is a lambda function?
Answer: Lambda function is an anonymous function that can be written in a single line.


# Normal function in python
def mul(a,b):
    return a*b

#lambda function
mul=lambda a,b : a*b

Question: Give the main difference between tuple and list.
Answer: Tuples are immutable whereas lists are mutable.


list1=[0,1,2,3,4] #list
tuple1=(0,1,2,3,4) #tuples
list1[2]=4 #Mutable
tuple1[2]=4 # it will through an error because tuples are immutable

Question: What is negative indexing in python??

Answer: Python data-types such as list, tuples, and sets support the positive as well as negative indexing. In negative indexing, if you pass -1 index it will call the last value of the list or if you call -2 indexing it will the second-last value of the list.





Question: What are the methods of a class?
Answer: Methods are the functions, which are defined inside a class.


class Animal:
    def method_1(self):
    def method_2(self):
        print(“hello world”)

Question: What is a __init__ method?
Answer: __init__ method is a reserved method of a class is also known as the constructor of a class. Whenever you initialize an instance of a class the __init__ method automatically calls.


class Animal:
    def __init__(self):
        print(“I am an Animal”)
    def method_1(self):
dog=Animal() #instance of a class


I am an Animal

Question: What are the Exceptions in Python?
Answer: Exceptions are the errors that occur during the execution of code.

Question: What Raises an Exception?
Answer: In python, you can raise an Error by using a statement raise and all the statements after it won’t execute.


raise ValueError



Question: Does Python have a concept of inbuilt Array?
Answer: Python does have a list but they are not Arrays. Python does not have support for in-built array data type but you can use the array with the help of a third-party library Numpy.

Question: What range function does in python?
Answer: range() is a special function often use in python it is used to iterate over a number of the sequence. range function can accept 3 arguments initial state, last state and the steps taken to reach the last point.


for i in range(2,10,2)



Question: What are dictionaries in python and how they are different from a list?
Answer: A dictionary is an in-built data type in python which consist of a pair of key and values separated by a colon(:).

Dictionary syntax:

dic= {“key1”: “value1”, “key2”:”value2”}

Dictionaries are the unorder collections of keys and values whereas a list is an ordered collection of values.

In the list, we use the index to call a value but in dictionaries, we use keys to call the corresponding value.

Question: What error will be shown if you index a key that is not a part of the dictionary?
Answer: KeyError.

Question: What is slicing in python?
Answer: Slicing gives more control to the user over a string or a list. With the help of slicing, you can retrieve any sequence of values that you want.


# List slicing
lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]


[“world”,6,”I am”]

Question: What is a class in Python?
Answer: A class is a blueprint of an object or instance that consists of a set of methods and attributes. A class has no existence until its object or instance has made.

Syntax of a class

class Animal:
    def method(self)

Question: What are tried and except statements?
Answer: Try and except statements are the part of exception handling. The try and except statements are similar to if and else statements but the difference is we use to try and except statements for the error handling.

If you write a code for the try block and if it through an error the try block stop being executed and the interpreter directly jumps to the except block to execute its code.

#syntax for try and execute statements

    print(“hello world”)
    print(“2”/3) #error
    print(“there is an error in the above statement”)


hello world
there is an error in the above statement

Question: What is an index in python?
Answer: In python to retrieve a specific value from a list, sting, or tuples we use the index. An Index is an integer which starts from 0 and every index corresponding to a value.

Question: What Assert statement does in python?
Answer: The assert statement checks whether the statement is True or False. If the assert statement is True nothing happens but if it is False the statement throws an AssertError.


assert 2+2==4
assert 2+2==5




Question: What is the object of a class?
Answer: An object is an instance of a class and a tool to access the properties and method of the class.

Question: What open() and close() functions do in python?
Answer: open() function is used to open a text file for reading, writing and appending purposes.

When you open the file for reading, writing or appending you also need to close it so close function helps to close the open file.

Question: What does a map function do in python?
Answer: A map() is an inbuilt function in python that takes 2 arguments. The 1st argument is the function and an iterable as its 2nd argument. The map function passes all the values of the iterable through the function one by one and at last returns a list.

#syntax for the map()

def mul3(num):
    return n*3


Question: How python can be used for web development?
Answer: Python has many frameworks like Django, flask, etc. which are used for web development, and you can simply get these frameworks by using pip install command.

Question: Explain filter() function.
Answer: filter() is an inbuilt function in python that is used to filter an iterable by removing items that do not match the predicate.

#filter syntax

res=list(filter(lambda x: x%2==0,lis))



Question: What are predicates?
Answer: Predicates are those functions which return a Boolean

Question: Does python support procedural programming?
Answer: Yes, though python is known for its object-oriented programming, python does support procedural programming.

Question: In python how can we use third-party libraries?
Answer: To use the 3rd party libraries first we need to install those. You can go to the python documentation to install the libraries or you can use the pip install command to install the libraries.

Question: What is a function?
Answer: A function is a set of code which is used to perform a task. This help to enhance the reusability of code. In python to declare a function, we use a keyword def.

Question: How many types of Function does python have?
Answer: Like another programming, language python has 2 types of function

  1. Built-in functions (functions already provided by the python)
  2. User-defined functions

Question: If we declare a function and do not define it what will happen?
Answer: The python interpreter will throw an error.

Question: If a function does not return anything will it throw an error?
Answer: No.

Question: What a break statement does?
Answer: A break statement terminates the loop statement and stops the iteration.


#break syntax
for i in range(4):
    if i==2:



Question: If a break statement uses inside the nested loop which loop it will terminate?
Answer: If we use a break statement inside a nested loop it will terminate the innermost loop.

Question: What do you understand by inheritance of class in python?
Answer: Inheritance is a way that helps to share the functionality of one class with another class. To inherit a class from another class we pass the base class name in the parentheses of derived or subclass.

Question: What are dunders in python?
Answer: Dunders is the special magic methods used in python which has 2 underscores at the beginning and end of their name. some e.g. of dunders methods are __init__, __str__, __del__,etc

What are the sets?
Answer: Sets are the unordered collections of data types that are immutable and do not accept the repetitive values. You are iterable but you cannot use index retrieves a value from a set.

#set syntax

{1,2,3,4,5,6} #it eliminates the repetitive values

Question: What are tuples?
Answer: Tuples are similar to a list, like the list in tuple we use indices to retrieve its values. The only difference is tuples are immutable whereas lists are mutable.


tup=(1,2,3,4,5) # to declare a tuple we use parentheses



Question: Can we use a list as a key of a dictionary?
Answer: No, the keys of the dictionary should be an immutable datatype such as tuples, strings or numbers.

Question: Why this statement often use in python if __name__==”__main__”: ?
Answer: __name__ is a special variable in the python which executes first before anything else. It uses with the if statement to check whether the file is executing directly or it’s being imported. If the file is running directly the __name__ variable will be automatically assigned “__main__” if not it assigned as the name of the file.

Question: What are *args?
Answer: *args is a special syntax that can accept a number of arguments pass to a function and treat those as a tuple.


def arg(*args):


<class ‘tuple’>

Question: What are **kwargs in python?
Answer: **kwargs are similar to *args, a special syntax which can accept a number of argument pass to function but in kwargs it treats the passed argument as a Dictionary.


def kwa(**kwargs):
kwa(x=”hello”, y=”world”,z=4)


{'x': 'hello', 'y': 'world', 'z': 4}
<class 'dict'>

Question: What does the end statement do in python?
Answer: Whenever we use a print() statement it always prints it on a new line. An end statement is an additional statement with the print() which have a value of ‘\n’ by default that’s why every print() statement print on a new line. We can manipulate the value of the end to change the print statement format.


print(“hello”, end=’ ‘)
print(“world”) #here end value id ‘\n’ by default
print(“go for”, end=”-“)


hello world
go for-it

Question: What is Django?
Answer: Django is one of the most widely used frameworks of Python.

Question: What does help() function do in python?
Answer: help() function shows the documentation related to the object passed in the help parenthesis.



Question: What are list comprehensions in python?
Answer: A list comprehension is a method of creating a new list from an iterable.


#List comprehension Syntax:
new_list=[i*2 for i in old_list]


[2, 4, 6, 8, 10, 12]

Question: What does a continue keyword do in python?
Answer: The continue statement jump back to the loop without executing the next statements.

#continue syntax

for i in range(10):
    if i>3:



Question: What ord() and chr() functions do in python?
Answer: The ord() return an ASCII code of the argument pass in it. Whereas the chr() perform adverse of ord(), it returns the corresponding value for the given ASCII code.





Question: What does isaplha() function do in python?
Answer: isalpha() is a special method used to check whether the given string containing only alphabets or not. If the string contains only alphabets the method will return true else it will return False.


print(“Hello 2”.isalpha())



Question: What does a split() function do?
Answer: split() is a function used with a string to get a list out of it. By default, the split function split the string into list values by using the white space.


str=’hello world I am here’


['hello', 'world', 'I', 'am', 'here']
['h', 'llo world I am h', 'r', '']

Question: What does title() and join() function do in python?
Answer: The title() function used with the string and it uppercase the first letter of each word and lowercase the rest.

The join() function used with tuples and list and it helps to join all the values of tuple or list altogether and return a string.


str="helLO woRld"


Hello World

Question: What is Python GIL?
Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock which allow only one thread to hold the control of the Python interpreter.

Question: How the python list is different from a linked list.
Answer: The Python list uses the contiguous memory location to store the list values like an array, whereas the linked List values do not store in a contiguous memory location.

Question: Name the library used to generate a random number?

Answer: Random Library


from random import randint



Question: What is recursion?
Answer: Recursion is a concept in which a function call itself it is also known as self-reference.


#Recursion Syntax in python
def fac(n):
    if n==1:
        return 1 # Base Case
        return n*fac(n-1)



Question: What is the base case of recursion and why do we need it?
Answer: A base case in a recursion refers to that statement that does not allow the function to further call itself. A base case is necessary for each recursion if you do not provide a base case to the recursion it will throw infinite results.

Question: How errors are different from the exception in python?
Answer: Error rise in a program due to some coding issue while exception occurs due to an interruption in the program by unusual inputs.

Question: What does for loop works in python.
Answer: For loop use an iterator to move from one point to another, it iterates from one value to the last of the iterators.

Question: Can we directly access a function that is defined inside another function?
Answer: No.

Question: What are decorators in python?
Answer: Decorators are one of the most powerful tools of python, which allow wrapping a function or class into another function to enhance its functionality.

Question: What would be the output of this code?


Answer: “world”

Question: What is a floor division?
Answer: It is similar to the normal division but in this, we use a double division sign to divide two integers and it returns an integer.


print(6//9) #floor division
print(6/9) # Normal division



Question: What are the Generators in python?
Answer: Generators are similar to the iterators such as list and tuples, which can be iterate with the help of for loop. To create a generator, we use functions and a special statement called yield. In simple words, generators are the function which yield output instead of returning.

#Generator Syntax

def rev():
    while i>0:
        yield i
for i in rev():



Question: What does yield statement do in python?
Answer: Yield statement used to define a generator, in the normal function we use return statement but in generators, we use yield statement to retrieve a result from a generator.

Question: How the yield statement is different from the return?
Answer: When we call a function if it has a yield statement then it will provide a sequence of results whereas a return statement will provide a specific value. A return statement terminates the function whereas the yield cannot.

Question: Write a code which show an equivalence to this code my_fun=my_dec(my_fun)
Answer: @my_dec

Question: What is NumPy?
Answer: Numpy is a very powerful and widely used package in python. The NumPY package id highly used for the data science and scientific research.

Question: What is a Docstring in python?
Answer: Docstring means documentation string and it is used to provide some additional information regarding the Python modules, Functions, Classes and Methods.

Question: What do we do to copy an object in python?
Answer: To copy an object, we use a copy module.

Question: What will be the output of the following code?




Question: What self-variable does in python classes?
Answer: Self is a conventional variable that is used as the first argument of every class method and it is used to hold the instance of the object.

Question: What are ternary operators in python?
Answer: Ternary operators are similar to the conditional operator and provide an alternative method to write the conditional operator code.

x= 35
min = x if x < y else y



Question: What is functional programming?
Answer: In functional programming, we can use a function as an argument and pass it to another function.


#Functional Programming
def fun1(fun2,arg):
    return fun2(fun2(arg))
def mul(n):
    return n*2



Question: What does del() function do in python?
Answer: The del() function is used to delete the object.

Question: What phenomena use when you transverse through a dictionary object in python?
Answer: Tuple unpacking

#Output key is key1 and values is val1 key is key2 and values is val2 key is key3 and values is val3

Question: Can we define a class inside a class in python?
Answer: Yes. OUTPUT Questions

Question: What would be the output of this code print(“5”*4)
Answer: #output 5555

Question: What would be the output of the following code a,b,*c=[1,2,3,4,5] print(a) print(b) print(c)
Answer: #output 1 2 [3, 4, 5]

Question: what would be the output? lis=[1,2,3,4,5,6,7] for i in range(4):


Answer: #Output

[2, 4, 6]

Question: what would be the output of the following code?




[[4], [4], [4]]

Question: what would be the output of the following code?

print(Lis1 is Lis2)




Question: What would be the Output of the following Code?




Question: What would be the output of the following code?




Question: What would be the output of the following code?



Question: What would be the output of the following code?

if a==b:




Question: Write code to add a delay of 1 min.

Question: What would be the output of the following code?

if id(lis1)==id(lis2):




Question: What would be the output of the following code?




[1, 2, 3]

Question: What would be the output of the following code?




Question: What would be the output of the following code?

def re():
    return "Hello"



Question: What would be the output of the following code?

if lis[1]in lis[0]:



Question: What would be the output?



[1, 2, 3, 1, 2, 3, 1, 2, 3]

Question: Name some main Features of Python for which it is Popular.

  1. It supports the Functional and structured Programming language, also follows the concepts of OOP’s.
  2. It is a dynamic language.
  3. It has a feature of Automatic Garbage collection.
  4. It is very easy to interpret.

Question: What is Python?
Answer: Python is a high level, interpreted, dynamic, and Object-oriented Programming language. It is written in the English language which makes it easier to read and understand.

Question: What is lambda in Python?
Answer: Lambda is a special function of Python which allows you to write a function in a single line.

Question: What for a keyword does in Python?
Answer: for is a loop which iterates a group of elements basically list.

Question: What is slicing a list or string?
Answer: Slicing a list or String means to select a specific range in a given sequence.

Question: What is the main difference between list and tuples?
Answer: lists are mutable it’s mean that you can change the value of lists but tuples are immutable you cannot change the values of tuples.

Question: What help() and dir() functions do?
Answer: help() function used to display the documentation string of the object which is placed inside the help function parenthesis.

While dir() function used to display the defined symbol and it returns None.

Question: Name the type of error for this syntax:

>>> k=14
>>> l = ”hello world”
>>> print(k+l)

Answer: TypeError, you cannot concatenate an integer and string directly, to do so you have to change the type of integer to string first.

Question: What is string concatenation and why do we use it?
Answer: String concatenation is a method that concatenates two strings. It’s used to combine two strings together.

>>> k= “hello”
>>> l= “world”
>>> p= k+l #string concatenation:
>>> print(p)

#output will be >>> helloworld

Question: What are Dictionaries in Python?
Answer: Python Dictionaries are the collections of keys and their corresponding values inside the curly braces.

>>> dict = {“one”: “its one”, “two” : ” its two”, “three” : “its three”}
>>> print( dict[“two”]) # here we are calling the dict value “its two” using key “two”
>>> its two # output

Question: How to convert any object to a string?
Answer: To convert any object to the string we use simple function str(); consider x is an object so to convert it to string we will write this statement str(x).

Question: What is a mutable built-in type in python?
Answer: There are some built-in types in Python which are mutable. By mutable means, their value can be manipulated which is already assigned.

Some examples of Mutable built-in types are:

  • List
  • Sets
  • Dictionaries

Question: Define immutable built-in type with its examples.
Answer: Immutable are those built-in types which value cannot be changed once it assigned.

Some examples of Immutable built-in types:

  • String
  • Tuples
  • Numbers

Question: What pass keyword do?
Answer: When you use pass keyword in your code it simply means that pass the just above statement or function and perform no operation. pass used when you need to leave some statement or function and want no operation to perform because python is an interpreted language and if you just leave any statement or function blank without any explanation it will show an error, so to ignore the error we use pass keyword.

Question: Java is the Static Data type and Python is Dynamic data type explain it.
Answer: When we use java we have to define the data type for each variable before we declare the variable which makes the Java a static type. But in Python we do not need to define the data type of each variable, so Python is a dynamic type.

Question: Comment on how memory managed in Python.
Answer: All the python memory is managed by Python Private Heap Space, all the data structure and Object are located in Private Heap and the Programmer does not have the access to the Private heap. It is a Python Interpreter that takes the full care of the Private heap.

Question: What are the Local variables?
Answer: When a variable is assigned inside a function is known as Local variable and only that specific function is allowed to use that variable.

Question: What are the global variables?
Answer: All those variables can be referenced by the function by using the global keyword.

Question: What is Django?
Answer: Django is a Full-stack web framework which is written in python and used to develop the dynamic web application.

Question: What are the module and packages in Python?
Answer: Module: Module is the Python Program file that can be imported to other python Program by using the import keyword

Packages: Packages are the folders which contain a bunch of python module and subfolders. Subfolders also contain modules.

Question: What split() function do.
Answer: split() function is basically used for split the string into a list

Question: What are Django, Pyramid, and flask in Python?

  • Django: Django is a full-stack Python web-framework.
  • Pyramid: Pyramid is also a Python web-framework that is used to build large web applications.
  • Flask: flask is a Python microframework that is basically used to build small web applications.

Question: What is map() function does in Python?
Answer: the map function accepts 2 arguments the first argument can be a function or statement and the 2nd argument is the type which iterates through the first argument.

Question: what is “None” often used to Represent?
Answer: Absence of value.

Question: What will be the output of this code?

foo= print()
if foo==None:

Answer: 1

Question: What is floor division?
Answer:  the symbol of the floor division is “//” double division sign it basically divides one value with another and give the answer an integer value.


p= 12//5



Question: Does python have a compiler?
Answer: Yes, python does have the compiler. It’s works automatically.

Question: Name all data types used in Python.

  1. Integer
  2. String
  3. List
  4. Tuple
  5. Dictionary

Question: Write the statement to reverse the list.
Answer: list.reverse()

Question: What are all the file processing mode in python?
Answer: 1. “r”= Used for reading the file

  1. “w”= used for write and overwrite on in the file or create the new file.
  2. “rw”= use for both read and write simultaneously
  3. “a”= it used for append the file and can create a new file too.

Question: Explain the concept of *args and ** kwargs.
Answer: *args , It is a special kind of function definition which is used to pass multiple variables as arguments to the function. *args basically used when you are not sure about how many arguments passed to the function.

# *args syntax:
def fun(*agrs): #here args is a variable you can choose other variable name too instead of args.
    for i in args:
fun(“hellow”,”world”,”its” ,“an”, “args”,”function”)



**kwargs: It is a special kind of function in python which allows the user to mass multiple argument in the function. But in **kwargs the argument passes in the function as dictionaries.

# e.g of **kwargs:

def fun(**kwargs):
    for k,v in kwargs.items():
        print(str(k) + “value is “+ str(v)
fun(k1=”value 1”,k2=”value 2”,k3=”value 3”)


k1 value is value 1
k2 value is value 2
k3 value is value 3

Question: How the Python interpreter work?
Answer: The Python interpreter consists of two things one is compiler and the second is a virtual machine. First, the compiler takes your source code and converts it into the Byte code. Byte code is simply a lower-level code that is platform-independent. Then the byte code is fed into the PVM(Python Virtual Machine). The PVM executes the Byte code and give the output.

Question: Explain the .py and .pyc file extension.
Answer: the .py is the file extension of the Python program, and .pyc is the file extension of the compiled byte code file which is generated by python.

Question: What is an Exception in python?
Answer: Exception can be defined as an event that occurs due to incorrect code or input.

Question: What we use to deal with the exception?
Answer: To avoid the exception we can use try/except statement. If any exception occurs, the code in try block stop execution and the code in the except block start to run.

# e.g.

except ZeroDivisionError:
    print(“error has occurred because of zero division”)


an error has occurred because of zero division

Question: What is raise an exception?
Answer: to raise the exception and terminate the program we can use raise exception statements.

# e.g.

raise ValueError



Question: Write all errors that occurred in python.

  • Import error: it occurs when the import statement fails
  • IndexError: when the indexing of any list fails
  • NameError: undefined or unknown variable
  • SyntaxError: when the code is not written properly
  • TypeError: when an unappropriated variable is a call.
  • ValueError: There are many other exceptions or errors in python. There are several exceptions in the third-party libraries.

Question: What is NumPy?
Answer: it is a fundamental package which is basically used for scientific computation with Python.

Question: Give some main features of NumPy.

  1. It has a powerful N-dimensional array
  2. Sophisticated functions
  3. tools for integrating c/c++ and Fortran code
  4. useful linear algebra, Fourier transform, and random number capabilities.

Question: What is list comprehension?
Answer: List comprehension is a method that can make the list in a concise way.


Lis=[i*I for i in range(10) if i%2==0]

Question: What is the difference between xrange() and range()?
Answer: both range() and xrange() shear the same properties, but the main difference occur in their return type. xrange() return the xrange object but the range return the list object.



There are many job roles for a python developer. A python developer could be a web-developer, Data Analyst, Data Scientist, Machine learning and Artificial Intelligent engineer. All the Python interview questions we have provided here cover mostly all the core python concepts with some advance python libraries. If you are going for a specific Job role and Python is just a tool you are using, then we suggest you read that Job interview questions. For instance, if you have a Django interview, we recommend you first read the Python interview questions and then read Django interview questions. This will help you to refresh your Python as well as Django skills.

If you like this article or have any suggestions, please let us know by commenting down below.


People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *