Top 44 Python Interview Questions & Answers: Ultimate Guide 2020

Attending a Python interview and wondering what are all the questions and discussions you will go through? Before attending a python interview, it’s better to have an idea about the types of python interview questions will be asked so that you can prepare answers for them.

Undisputed one of the most popular programming languages these days, Python is a hot choice for both established and beginner programmers. And, ease of the language helps develop some interesting Python Projects that are applicable in the real world. Its simplicity and ease of use lend to its popularity. Not to mention, it is the language of choice for the data science and data visualization fields, along with R.

data analyst interview questions and answers

That being said, Python is a very important language for anyone’s toolkit. To help you out, I have created the top python interview question and answers guide to understand the depth and real-intend of python interview questions. 

Apart from these questions, you will also be given code snippets where you have to deduce the resulting value or statement (or the lack of it). These cannot be predicted and will be dependent on your programming practice. Let’s get started with top python interview questions and answers. 

Python Interview Questions & Answers 2020


Q 1) What is the difference between a module and a package in Python?

A 1) Each Python program file is a module that imports other modules like objects. Thus, a module is a way to structure the program. The folder of a Python program is called a package of modules.

Q 2) What are the built-in types available in Python?

A 2) One of the most common python interview question, There are mutable and immutable built-in types.

The mutable ones include:

  • List
  • Sets
  • Dictionaries

The immutable types include:

  • Strings
  • Tuples
  • Numbers

Q 3) What is lambda function in Python?

A 3) It is often used as an inline function and is a single expression anonymous function. It is used to make a new function object and return them at runtime.

Lambda is an anonymous function in Python that can accept any number of arguments and can have any number of parameters. However, the lambda function can have only a single expression or statement. Usually, it is used in situations that require an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

Here’s an example of the lambda function:

a = lambda x,y : x+y 

print(a(5, 6))

Output: 11

Q 4) What is meant by namespace?

A namespace refers to a naming system that is used to ensure that all object names in a Python program are unique, to avoid any conflicts. In Python, these namespaces are implemented as dictionaries with ‘name as key’ mapped to a corresponding ‘object as value.’ As a result, multiple namespaces can use the same name and map it to a different object. 

Below are the three types of namespaces in Python: 

  • Local namespace – It includes local names inside a function. A local namespace is temporarily created for a function call and is cleared when the function returns.
  • Global namespace – It consists of the names from various imported packages/ modules that are currently being used in a project. A global namespace is created when a package is imported in the script, and it lasts until the script is executed.
  • Built-in namespace – It includes built-in functions of core Python and built-in names for the different types of exceptions.

Q 5 ) Explain the difference between a list and a tuple?

A 5) The list is mutable while the tuple is not. Tuples can be hashed as in the case of making keys for dictionaries.

Q 6) Difference between pickling and unpickling?

Any Python Interview Question and Answers guide won’t complete without this question. In Python, the pickle module accepts any Python object, transforms it into a string representation, and dumps it into a file by using the dump function. This process is known as pickling. The function used for this process is pickle.dump().

On the other hand, the process of retrieving the original Python object from the stored string representation is called unpickling. The function used for this process is pickle.load().

Q 7) What are decorators in Python?

A 7) A Python decorator is a specific change made in the Python syntax for the easy alteration of functions.

Q 8) Difference between generators and iterators?

A 8) In Python, iterators are used to iterate over a group of elements (in a list, for example). The way of implementing these iterators is known as generators. It yields an expression in the function, but otherwise behaves like a normal function.

Q 9) How to convert a number into a string?

A 9) One of the most common python interview questions. We can use the inbuilt str() function. For an octal or hexadecimal representation, we can use the other inbuilt functions like oct() or hex().

Q 10) What is the use of the // operator in Python?

A 10) Using the // operator between 2 numbers gives the quotient when the numerator is divided from the denominator. It is called the Floor Division operator. 

Q 11) Does Python have a Switch or Case statement like in C?

A 11) No, it does not. However, we can make our own Switch function and use it. 

Q 12) What is the range() function and what are its parameters?

A 12) The range() function is used to generate a list of numbers. Only integer numbers are allowed, and hence, parameters can be both negative and positive. The following parameters are acceptable:


Where ‘stop’ is the no. of integers to generate, starting from 0. Example: range(5) == [0,1,2,3,4]

range([start], stop[, step])

Start: gives the starting no. of the sequence

Stop: specifies the upper limit for the sequence

Step: is the incrementing factor in the sequence

Q 13) What is the use of %s?

A 13) %s is a format specifier which transmutes any value into a string.

Q 14) Is it mandatory for a Python function to return a value?

A 14) No

Q 15) Does Python have a main() function?

A 15) Yes, it does. It is executed automatically whenever we run a Python script. To override this natural flow of things, we can also use the if statement. 

Q 16) What is GIL?

A 16) GIL or the Global Interpreter Lock is a mutex, used to limit access to Python objects. It synchronizes threads and prevents them from running at the same time.

Q 17) Before the use of the ‘in’ operator, which method was used to check the presence of a key in a dictionary?

A 17) The has_key() method

Q 18) How do you change the data type of a list?

A 18) To change a list into a tuple, we use the tuple() function

To change it into a set, we use the set() function

To change it into a dictionary, we use the dict() function

To change it into a string, we use the .join() method

Q 19) What are the key features of Python?

A 19) It is one of the common python interview questions. Python is an open-source, high-level, general-purpose programming language. Since it is a general-purpose programming language and it comes with an assortment of libraries, you can use Python for developing almost any type of application.

Some of its key features are:

  • Interpreted
  • Dynamically-typed
  • Object-oriented
  • English-like syntax

Q 20) Explain memory management in Python.

A 20) In Python, the Python Memory Manager takes care of memory management. It allocates the memory in the form of a private heap space that stores all Python objects and data structures, there are 4 built in data structure in python. This private space is inaccessible to the programmer. However, the core API allows the programmer to access some tools for coding purposes. Plus, Python is equipped with an in-built garbage collector that recycles the unused memory for the private heap space.

Q 21) What is PYTHONPATH?

A 21) PYTHONPATH is an environment variable that is used to incorporate additional directories when a module/package is imported. Whenever a module/package is imported, PYTHONPATH is used to check if the imported modules are present in the existing directories. Usually, the interpreter uses PYTHONPATH to determine which module to load.

Q 22) Is Python case-sensitive?

A 22) A programming language is deemed to be case-sensitive if it distinguishes between identifiers like “myname” and “Myname.” In simple words, it cares about the case – lowercase or uppercase. 

Let’s see an example:

  1. >>> myname=’John’
  2. >>> Myname

Traceback (most recent call last):

File “<pyshell#3>”, line 1, in <module>


NameError: name ‘Myname’ is not defined

Since it raises a NameError, it means that Python is a case-sensitive language.

Read more: Python Pandas Tutorial

Q 23) Explain the use of “help()” and “dir()” functions.

A 23) In Python, the help() function is used for showing the documentation of modules, classes, functions, keywords, and so on. If the help() function receives no parameter, it launches an interactive help utility on the console.

The dir() function is used to return a valid list of attributes and methods of the object it is called upon. Since the function aims to produce the most relevant data (instead of showing the complete information), it behaves differently with different objects:

View Course
  • For modules/library objects, the dir() function returns a list of all attributes contained in that module.
  • For class objects, the dir() function returns a list of all valid attributes and base attributes.
  • When no parameters are passed to it, the dir() function returns a list of attributes in the current scope.

Q 24) What are python modules? Name some commonly used built-in modules in Python?

A 24) Python modules are files containing Python code that can be either function classes or variables. These modules are Python files having a .py extension. Modules can include a set of functions, classes, or variables that are both defined and implemented. You can import and initialize a module using the import statement, learning python tutorial will let us know more about python modules.

Here are some of the commonly used built-in modules in Python:

  • os
  • sys
  • math
  • random
  • data time
  • JSON

Q 25) Explain “self” in Python.

A 25) In Python, “self” is a keyword used to define an instance or object of a class. Unlike in Java, where the self is optimal, in Python, it is primarily used as the first parameter. Self helps to distinguish between the methods and attributes of a class from its local variables.

The self variable in the __init__ method refers to the newly created object or instance, while in other methods, it pertains to the object or instance whose method was called.

 Q 26) What is PEP 8?

A 26) PEP or Python Enhancement Proposal is a set of rules that specify how to format Python code for maximum readability. It is an official design document that provides relevant information to the Python Community, such as describing a new Python feature or a Python process. PEP 8 is an important document that includes the style guidelines for Python Code. Anyone who wishes to contribute to the Python open-source community must strictly abide by these style guidelines.

Q 27) Is indentation mandatory in Python?

A 27) Yes, indentation is necessary for Python. Indentation helps specify a block of code. Thus, in a Python code, everything within loops, classes, functions, etc., is specified within an indented block. If your Python code isn’t indented correctly, there’ll be problems during the execution, and it will raise errors. 

Q 28) Explain the difference between Python arrays and lists.

A 29) In Python, both arrays and lists are used to store data. However,

  • Arrays can only contain elements of the same data types, meaning the data types of an array should be homogeneous.
  • Lists can contain elements of different data types, which means that the data types of lists can be heterogeneous. Lists consume much more memory than arrays. 

Here’s an example:

import array as arr





Q 29) What is __init__?

A 29) In Python,__init__ is a method or constructor. It is automatically called to allocate memory when a new object or instance of a class is created. All classes have the __init__ method.

Here’s how to use the __init__ method in Python:

# class definition

class Student:

    def __init__(self, fname, lname, age, section):

        self.firstname = fname

        self.lastname = lname

        self.age = age

        self.section = section

# creating a new object

stu1 = Student(“Sara”, “Ansh”, 22, “A2”)

Q 30) Explain the functionality of “break,” “continue,” and “pass.”

A 30) It is one of the common questions in python interview questions and answers guide. Let’s see break, continue and pass in detail.

The break statement is used for terminating a loop when a specific condition is met, and the control is transferred to the following statement.

  • The continue statement helps to terminate the current iteration of the statement when a particular condition is met, skips the rest of the code in the current iteration, and passes the control to the next iteration of the loop.
  • The pass statement is essentially a null operation that is used to fill up empty blocks of code that may execute during runtime but are yet to be written. It is represented by a semi-colon.

Q 31) How to write comments in Python?

A 31) In Python, comments start with a # character. However, sometimes, you can also write comments using docstrings(strings enclosed within triple quotes). Unlike C++, Python does not support multiline comments.

Here’s how a comment is written in Python:

>>> #line 1 of comment

>>> #line 2 of comment

Q 32) What are the generators in Python?

A 32) Generators are most important python functions that return an iterable collection of items, one at a time, in an organized manner. Generally, generators are used to create iterators with a different approach – they use of yield keyword rather than return to return a generator object.

Q 33) How can you capitalize the first letter of a string in Python?

A 33) In Python, you can use the capitalize() method to capitalize the first letter of a string. However, if a string already consists of a capital letter at the beginning, it will return the original string.

Q 34) What are “docstrings” in Python?

A 34) Docstrings or documentation strings are multiline strings used to document a specific code segment. Docstrings usually come within triple quotes and should ideally describe what a function or method does. Although they are not comments, docstrings sometimes serve the purpose of comments since they are not assigned to any variable.

Q 35) Explain the functions of “is,” “not,” and “in” operators?

A 35) Again, one of the popular python interview questions. Operators are special functions in Python that can take one or more values to produce a corresponding result. 

  • The “is” operator returns true when two operands are true.
  • The “not” operator returns the inverse of the boolean value.
  • The “in” operator checks if some element is present in some sequence.

Q 36) How to copy an object in Python?

A 36) In Python, the assignment statement (= operator) does not copy objects, but instead, it creates a binding between the existing object and the target variable name. Thus, if you wish to create copies of an object in Python, you need to use the copy module. There are two ways to create copies for a particular object using the copy module:

  • Shallow copy – It is a bit-wise copy of an object. The copied object will have an exact replica of the values contained in the original object. If any of the values are references to other objects, only the reference addresses for the same will be copied.
  • Deep copy — It copies all values recursively from source to target object, meaning, it will duplicate even the objects that are referenced by the source object.

Q 37) What is an Expression?

A37) An expression Can be defined as a combination of variables, values operators a call to functions. It is a sequence of operands or operators like a + B – 5 is called an expression. Python supports many such operators for combining data object into an express.

Q 38)What is a statement in Python?

A38)It is an instruction that Python can interpret and execute when you type the statement in the command line Python execute and displays the result if there is one.

Q 39)What is ==  in Python?

A39)It is an operator which is used to check or compare the values  of two objects

Q 40)What are the escape sequences in Python?

A40) Python strings, the backslash “\” could be a special character, also called the “escape” character. it’s utilized in representing certain whitespace characters: “\t” may be a tab, “\n” could be a newline, and “\r” could be a printing operation. Conversely, prefixing a special character with “\” turns it into a standard character.

Q 41)what is encapsulation?
A41) Encapsulation is the binding of data and functions that manipulate the data.
It is a process of wrapping up data and variables together.

class playercharacter():
def __init__(self,name,age): = name
self.age = age

player1 = playercharacter(‘leo’,25)

Q42) How do you do data abstraction in Python?
A42) An abstraction means hiding away information or showing only information that’s necessary.
#in this example we dont want to learn how len was introduced in python

Q43) What is a dictionary in pthon?
A43) Dictionary is a data structure as well as a data type in python.It is enclosed in curly brackets{}.
Dictionary contains 2 elements – key and value
key is a string for us to grab a value.

dictionary = {
‘a’: 1,
‘b’: 2


Q44) What are functions?
A44) Functions are a set of code used when we want to run the same method for more than 1 time.It reduces the length of program.Functions are defined into 2 categories –
1)function defination
2)function calling

def dog():
print(“my name is tommy”)



We hope our Python Interview Questions and Answers guide is helpful. We will be updating the guide regularly to keep you updated.

The above list of questions, paired with your own practice on the PC, will help you to crack any and every Python interview ever. Apart from the basics, the only thing left is to practice so that while the interviewer is asking you questions, your mind is already writing and executing the code with it. 

If you are curious to learn more about data science, check out IIIT-B & upGrad’s PG Diploma in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Prepare for a Career of the Future

Join Now

Leave a comment

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

Download Whitepaper
Download Whitepaper
By clicking Download Whitepaper, you agree to our terms and conditions and our privacy policy.
View Course
Aspire to be a Data Scientist
Download syllabus & join our Data Science Program and develop practical knowledge & skills.
Download syllabus
By clicking Download syllabus, I authorize upGrad and its representatives to contact me
via SMS / Email / Phone / WhatsApp / any other modes.
I agree to upGrad terms and conditions and our privacy policy.