• Articles
  • Tutorials
  • Interview Questions

Python Interview Questions and Answers

Tutorial Playlist
career-aspirant learners have read this article
Reviewed and fact-checked by
Principal Data Scientist


Most Frequently Asked Python Interview Questions

  1. What is Python and what are its benefits?
  2. How is memory managed in Python?
  3. In the given array, write a list comprehension that will print the sum of even numbers.
  4. What are loops in Python? How do you write a nested for loop program?
  5. What are collections? What is the significance of collections in Python?
  6. What is String Manipulation, Give a few examples.
  7. What is __init__ in Python?
  8. What is the difference between modules and libraries?
  9. What is the purpose of “is”, “not” and “in” operators?
  10. How will you reverse a list in Python?

Watch this video on Python interview questions and answers:

Python Basic Interview Questions for Freshers

1. Find the frequency of each letter in the given string.

String = ‘the quick brown fox jumps over the lazy dog.’

We have the problem statement wherein we have to find out the frequency of each letter in the given string i.e we have to find out how many times each letter is occuring.

Let’s define our approach towards the problem statement:

  1. We will make use of a dictionary to store the result, why? Because you see we can keep the result in the form of a key-value pair. How? The alphabets out there are our key and the occurrence that we have to find out will be our values.
  2. We can make use of a For Loop to traverse through the string and for every loop we will count the number of times the characters are occurring using the count().

But before that we also have to do a bit of data cleaning. If you properly observe the string, it has spaces and punctuations in there. So if we don’t remove it, it will eventually be counted and that is something we don’t want. So as to remove the punctuation we will make use of the lambda and the filter() along with the isalpha(), isdigit() and isspace() function.

Now that we are clear with the approach lets write down the code:

# The original input string
OriginalString = "The quick brown fox jumps over the lazy dog."

# Splitting the string and removing spaces and punctuation.
CleanedString = ''.join(filter(lambda x: x.isalpha() or x.isspace() or x.isdigit(), OriginalString.split()))

# To Bring Consistency in the string, converting everything to lowercase
CleanedString = CleanedString.lower()

#dictionary comprehension for the frequency count 
result = {x: CleanedString.count(x) for x in CleanedString} 

# Printing the result dictionary


{‘t’: 2, ‘h’: 2, ‘e’: 3, ‘q’: 1, ‘u’: 2, ‘i’: 1, ‘c’: 1, ‘k’: 1, ‘b’: 1, ‘r’: 2, ‘o’: 3, ‘w’: 1, ‘n’: 1, ‘f’: 1, ‘x’: 1, ‘j’: 1, ‘m’: 1, ‘p’: 1, ‘s’: 1, ‘v’: 1, ‘l’: 1, ‘a’: 1, ‘z’: 1, ‘y’: 1}

2. Write a program in Python to find the largest and second-largest element in a list using Python?

Here the problem statement says that we have to find out the largest and second largest element from a list containing.

The approach towards such a problem statement is simple. We will sort the list in ascending order using the sorted() and then with the help of negative indexing we will be returning the last and the second last element.

negative indexing


# Defining a function
def LargestAndSecondLargest(Data):
  # Sorting the list in Ascending Order
  Data = sorted(Data)
  # Extracting the last element (Largest Element)
  largestElement = Data[-1]
  # Extracting the second last element (Second Largest Element)
  SecondlargestElement = Data[-2]
  # Returning the variables containing the elements.
  return largestElement, SecondlargestElement

Data = [20,15,8,12,19]

(78, 10)

3. Create a Python program that will print the highest sequence of 1s in an array of 0s and 1s?

a = [1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1]
# Variable to Store the count of one
countofOne = 0
# Variable to Store the previous count only if the countofOne is greater than the LastCountofOne
LastCountofOne = 0

# For Loop to traverse through all the element in the array
for i in range(len(a)):
  # Check if the element is 1
  if a[i] == 1:
    # Count increased by 1
    countofOne += 1
    # Checking if countofOne > LastCountofOne
    if(LastCountofOne < countofOne):
      # Swapping the value to LastCountofOne if the above condition is True
      LastCountofOne = countofOne
      # Set countofOne to zero as we are interrupted by zero
      countofOne = 0

# Comparing the last value of countofOne with LastCountofOne
if(LastCountofOne > countofOne):
  # Print LastCountofOne
  # Print countofOne


4. In the given array, write a list comprehension that will print the sum of even numbers.

reverse a string

First of all, we have to understand what an Even Number is. An even number is a number that when divided by 2 leaves a remainder 0 (zero). To return the remainder in a division we make use of the modulus operator(%).

Here is the approach we are following for the problem statement:

  1. Looping through all the elements in a list using For Loop
  2. Checking if the element leaves a remainder zero on division by 2 (x%2 == 0)
  3. If the condition seems to be True add it to the Sum counter initialized as zero
  4. Lastly printing the Output as the sum of all even numbers in a list.

Now that we are clear about our approach to the problem statement. Let’s have a look at the program below:

# Sample Data in a List
sample = [1,2,3,4,5,6,7,8,9,10] 
# Defining the variable sum to zero
Sum = 0
# Looping through elements in the list and checking if it is an even number or not and adding
Sum = sum([x for x in sample if x%2 == 0])
# Printing the Sum of Even Numbers


5. Write a function to output separate lists containing even and odd elements from a given array.

Let’s take a look at the program, here our approach is written as follows:

  1. Check if the given element is even or odd
  2. Return two separate lists with even and odd elements
# Defining a Function
def EvenOdd(Data):
  # Checking if the number is even
  print([x for x in Data if x%2 == 0])
  # Cheking if the number is odd
  print([x for x in Data if x%2 != 0])

# Sample Data
Data = [1,2,3,4,5,6,7,8,9,10]
# Function Call


[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

The above program will create two separate lists after checking if the elements are even or odd in the given sample, and print both the lists at the end of the execution.

6. What is file handling in Python? What are the various file-handling operations in Python?

File handling also known as Python I/O involves working with files on a computer’s file system using Python as a programming language.

Python File Handling Operations can be categorized into the following categories:

  1. Reading a file
  2. Creating a file
  3. Writing in a file
  4. Deleting a file

Have a Look at this blog on File Handling in Python

7. Create a Python program to depict the functioning of stacks and queues?

# Program to show the implementation of stack

stack = []
x = list(range(0,10,3))
for i in range(1,6):
  if i < len(x):

[3, 6]
[3, 6, 9]
[3, 6]

# Program to show the implementation of Queue - FIFO

#Implementation of Queue - FIFO
queue = []
x = list(range(0,10,3))
for i in range(1,6):
  if i < len(x):

[3, 6]
[3, 6, 9]
[6, 9]

8. Write a Python program to print a list of primes in a given range.

In this program where we need to check if the number is a prime number or not, we are making use of a very simple approach. Firstly we need to understand what is a Prime Number? A whole number greater than 1 cannot be exactly divided by any whole number other than itself and 1.

Let’s formulate the approach:

  1. Check if the number is greater or less than 1. If less than one returns that it is not a prime number immediately as the definition says “A Whole number greater than 1”
  2. If not less than one, check if the number has some other factors or not. If it has returned that it is not a prime number.
  3. Lastly, if it passes all the tests returns that it is a prime number. 

Now let’s have a look at the program to check if the number is a prime number or not.

# Defining a Function
def isPrime(num):
  # Checking if num > 1 because there are no prime numbers less than 1
  if(num > 1):
    # Looping through the elements in a range of 2,num to find factors
    for i in range(2,num):
        # if three is a factor other than 1
        if(num % i == 0):
            # Return Fales in Flag i.e not a prime number
            flag = False
            # End the Loop
        # If there is no factor other than 1 return True in Flag
        flag = True
      # IF the number is less than 1 return False in Flag
      flag = False
  # Finally return the Final value of the flag
  return flag

# Sample input
num = 5
# Check if the flag is True or False
if (isPrime(num)):
  # If Flag is True print
  print("It is a Prime Number")
  # If Flag is False print
  print("It is a not a Prime Number")

9. What are loops in Python? How do you write a nested for loop program?

In Python programming, a loop is a sequence of instructions that gets executed repeatedly until and unless an exit condition is reached.

Let’s take a problem statement to understand the usage. Let’s say I want to print “Python” 5 times. There are multiple ways of approaching the same problem statement. One is, writing the print statement 5 times, as shown below:


But now, if I want to print it 100 times or let us say, 1000 times, will I be writing the print statement 1000 times? Though that is possible, it is an inefficient way of approaching a problem statement. Here Loops comes to rescue, which helps us to execute a block of code again and again.

There are two types of loops in Python:

  1. For Loop: For loop is mostly used in cases where we have range data or problems with sequential traversal, like traversing a list, string or an array.
    Here is the syntax for For Loop:

    for iterator_var in sequence:
    statements(s) to be executed

    If we take up the previous problem statements of printing “Python”, 5 times, but now using a for loop. It will be as shown below:

    for i in range(0,5):

In the above code, we are using the range function to generate a range of 0 to (n-1) i.e (5-1) = 4. The iterator_var, here referred to as ‘ i ’ will traverse through all the elements in the range (0,1,2,3,4). And for each time the loop runs “Python” will get printed. It can be better understood with the help of a dry run as shown below:

Value of i Print Python Next value of i from range
0 Python 1
1 Python 2
2 Python 3
3 Python 4
4 Python Range ends, Exit Loop
  1. While Loop: While loops are mostly used in such cases, where we want to run a block of code repeatedly until and unless a condition is satisfied.

Here is the syntax for While Loop:

Iterator_var = 0
while expression:
    Iterator_var increment

If we take up the previous problem statements of printing “Python”, 5 times, but now using a while loop. It will be as shown below:

count = 0
while (count &amp;amp;lt; 5)
    count = count + 1

In the above code, we are setting a count variable to 0 that will count the number of times Python is getting printed. Then, we have the while loop that checks for the condition if it is true, Python gets printed, and the count gets incremented by 1 every time until and unless exit condition is reached. Here is the dry run given below:

count while(count > 5) Print Python count = count + 1
0 TRUE Python 1
1 TRUE Python 2
2 TRUE Python 3
3 TRUE Python 4
4 TRUE Python 5
5 FALSE Exit Condition Reached, Loop Exits

In Python, a Loop within another loop is called a Nested Loop. This is applicable for both For Loop and While Loop. Below are the code snippets for Nested For Loop and Nested While Loop:

Nested For Loop:

for iterator_var in sequence:
   for iterator_var in sequence:

Nested While Loop:

while expression:
   while expression: 

10. What are collections? What is the significance of collections in Python?

Collections refer to those data structures or containers that are capable of holding collective data in a single variable. 

Let’s take an example to understand it. Suppose you have lots of books and are trying to build a library. Each book is different, some are about life lessons, some are about stories, and some are about magic, etc. In Python, collections are like those collections of books. They help you organize lots of things (like numbers, words, or other data) in an organized way, just like how you organize your books in your library.

There are four different data structures in collections:

List: List is one of the most versatile data structures in python. Here are the characteristics of a list to be remembered:

  • Lists are mutable data types i.e once declared, a list can be modified.
  • Lists can contain heterogeneous elements i.e elements with different data types.
  • Lists also allow duplicate values.
# This is an empty list	
Mylist = []
# Let's add some values to it
Mylist = [1,2,"Intellipaat", "Live", 23.45, True]
# Printing the list

Tuple: Tuples are similar to lists, they are usually used to store related data. Here are the characteristics of a list to be remembered:

  • Tuples are immutable data types, i.e once declared, a tuple can’t be modified.
  • Tuple can contain heterogeneous elements i.e elements with different data types.
  • Tuples also allow duplicate values.

Here is the syntax to define a tuple:

# This is an empty tuple
MyTuple = ()
# Let's add some values to it
MyTuple = (1,2,"Intellipaat", "Live", 23.45, True)
# Printing the tuple

Dictionary: Think of them like real-world dictionaries where you look up a word (key) to find its definition (value). Here are the characteristics of a list to be remembered:

  • Dictionaries are mutable data types i.e once declared, can be modified later.
  • Dictionaries can contain heterogeneous elements i.e elements with different data types.
  • Dictionaries store data in the form of Key, Value pairs.
  • Dictionaries cannot have two elements with the same key.

Here is the syntax to define a dictionary:

# This is an empty dictionary
MyDict = {}
# Let's add some values to it
MyDict = {"Name": "Intellipaat", "Industry": "EdTech", "Revenue": 120}
# Printing the dictionary

Set: Sets are useful for tasks like removing duplicates from a list or performing mathematical set operations like union, intersection, and difference. Here are the characteristics of a list to be remembered:

  • Sets are unordered, i.e the items in a set do not have a defined order.
  • Sets are mutable data types i.e once declared, can be modified later.

Here is the syntax to define a dictionary:

# This is an empty set
MySet = {}
# Let's add some values to it
MySet = {1,2,"Intellipaat", "Live", 23.45, True}
# Printing the set

The significance of collections in Python is to handle complex data structures and algorithms efficiently. By choosing the right collection for the task at hand, you can write cleaner, more organized code that is easier to understand and maintain.

11. Write a program to check even odd numbers using shorthand if else statements.

Before directly jumping onto writing the program, lets understand what is the ultimate goal, the ultimate goal of the program should be checking if a number is odd or even. 

Let’s first understand even and odd numbers. When can a number be even? A number is even when it is divided by two and returns a remainder zero. Now we know that the remainder can be determined with the help of the modulus function (%), which returns the remainder of the division. Now, let’s go ahead and write the program.

# Defining the Function
def EvenOdd(n):
  print("Even Number") if(n%2 == 0) else print("Odd Number")

# Calling the Function:
EvenOdd(21) # Output: Odd Number
EvenOdd(12) # Output: Even Number

12. Write a Python program that will reverse a string without using the slicing operation or reverse() function?

reverse a string

# Defining the function
def reverseString(x):
  # Declaring an empty String
  NewString = ""
  # Traversing through individual characters in a string
  for i in x:
    # Add the character to the empty string
    NewString = i + NewString
  # return the new string
  return NewString

# Sample String
string = "Intellipaat"
# Function Call
ReversedString = reverseString(string)
# Printing Output


13. Write a Python program that removes duplicates from a list?

Removing duplicates from a list can be done very easily by converting the list into a set and then back to a list. As it is a property of a set that can only contain unique.

# Sample Data in List
Sample = [1,1,0,0,1,0,2,0,3,2,2,4,4,2,3]
# Converting the list to set to remove duplicates
SetSample = set(Sample)
# Converting the set to a list again
ListSample = list(SetSample)
# Printing the Output

[0, 1, 2, 3, 4]

14. What is method overriding? Explain with an example in Python?

Method overriding is a polymorphism concept where a method overrides its parent class method during inheritance. Let’s take a look at a simple example:

class Animals:
  def species(self, x):
    self.x = x
    print("species of the animal is : {}".format(self.x))

class Snakes(Animals):
  def species(self):
    print("Species is Reptiles")

#calling the parent class method
obj = Animals()

#calling the class object overrides the parent class method
obj1 = Snakes()

species of the animal is : Amphibian
Species is Reptiles

15. What is String Manipulation, Give a few examples.

A string is a collection of letters or characters. String manipulation is the process of modifying the characters of a string. It involves various operations, such as changing the letter cases, slicing, and concatenating two or more strings. In Python, there are several pre-built functions that we can use to modify a string.

Here are a few examples of string manipulation:

String Concatenation: It is a method of combining two or more strings together. Let us understand it using a very simple Python program:

str1 = "Hello" #first string
str2 = "World" #second string
result = str1 + "  " + str2 
print(result)  #output: Hello World

In this code, we have created two variables, str1 and str2 which are storing two strings, “Hello” and “World”. Then, we have created a third variable in which we are storing the final output. Using the “+” operator, we are concatenating two strings.

Slice a string: It is a process of extracting substrings from a string. Let us see how we can perform the string slicing.

str = "Intellipaat"
substring = str[0:7] 
print(substring)  # Output: Intelli

In this code, we have a str variable storing “Intellipaat‘. We are extracting a substring from a string using the indexes str[start_index:end_index]. This method allows us to extract a portion of a string by specifying a start index and an end index. In this case, the start index is 0 and the end index is 7 (excluding 7).

Split a string: Dividing a string into a list of substrings.

In this code, we are splitting the str string into two words:  “Hello” & “World”. The final output we will get is a list of words.

str = "Hello,World"
fruits = str.split(",") # Here we have used a split method to split the string into two substrings based on the specified delimiter, which is a comma in this case.

# Output: [‘Hello’, 'World’]

Case conversion: Using the lower or upper functions, we can change the cases of strings. Here is a very simple python program to convert the case of a string:

str = "Intelli Paat"
lowercase_str = str.lower() # This built-in function is going to convert all the string letters to lower case
uppercase_str = str.upper() # And this one will convert all the string letters to upper case.
print(lowercase_str)  # Output: intelli paat
print(uppercase_str)  # Output: INTELLI PAAT

Reverse a string: Here is an example of how we can reverse a string. 

In this code, we are using slicing to reverse a string.

str = "Hello World"[::-1]

#Output: dlroW olleH

16. What is Python and what are its benefits?

Python is a high-level,  interpreted, general-purpose, and dynamically-type language known for its simplicity and readability. This programming language supports various programming paradigms, structured programming, functional programming, and object-oriented programming (OOPs). It was developed by Guido Van Rossum in 1991. Python is popular among developers as its code is usually smaller and easier to understand as compared to Java or C. Python is widely used in Web Development, Machine Learning, Data Analysis, and Data Science. Python is designed to be highly readable and compatible with different platforms, such as Mac, Windows, Linux, Raspberry Pi, etc.

Benefits of using Python: 

  • Python is easy to learn because of its simplicity.
  • Python has the support of a wide variety of third-party libraries or packages.
  • Python has a very active and large community over the internet.
  • Python is a high-level programming language that hides low-level details, making it more user-friendly.
  • Python is portable across operating systems
  • Python is dynamically typed, i.e. there is no need to declare data types explicitly

Python is one of the most demanding skills right now in the market. Enroll in our Python Certification Course and become a Python Expert.

17. Is Python interpreted or hybrid?

Various books and articles on the internet consider Python as an Interpreted Language. But when we write a Python program, it is first compiled and then interpreted. In the compilation part when we execute our code, a byte code is generated. This byte code internally gets converted by the Python Virtual Machine (PVM). As soon as our code gets executed the compiler part gets deleted immediately. So keeping all of these characteristics of python in mind, we can term it as a Hybrid Language.

18. What distinguishes lists from tuples?

 Here are the major differences between List and Tuples: 

Lists Tuples
Lists are mutable, i.e., they can be edited Tuples possess immutability, denoting their incapability of being modified like lists.
Lists are usually slower than tuples Tuples are faster than lists
Lists consume a lot of memory Tuples consume less memory comparatively
Lists have a higher likelihood of experiencing unexpected changes, making them less reliable in terms of errors Tuples offer increased reliability due to their resistance to unexpected modifications

19. What is PEP 8?

PEP in Python stands for Python Enhancement Proposal. It comprises a collection of guidelines that outline the optimal approach for crafting and structuring Python code to improve readability and clarity of the code.

20. What are the key features of Python?

What are the key features of Python

The key features of Python are as follows:

  • Python is a Free and Open source programming language i.e. Python is available to all for free and anyone as a developer can contribute to the code.
  • Python is a high-level programming language that makes it easy for the user to read, understand, and learn the language.
  • Python is an object-oriented programming language except having access specifiers. Other than access specifiers (public and private keywords), Python has classes, inheritance, and all other usual OOPs concepts.
  • Python has gained a lot of popularity over the years as a result of which it has a large community.
  • Python is a portable language i.e. a code written on Mac can also run on Windows.

Python has the support of a wide range of standard libraries as well as third-party libraries.

Go through the Data Science with Python Course in Hyderabad to get a clear understanding of Python and become a Python developer today!

Get 100% Hike!

Master Most in Demand Skills Now !

21. How is memory managed in Python?

  • Python makes use of automatic memory management through garbage collection.
  • The garbage collector keeps track of objects and frees memory when they are no longer in use.
  • Python uses reference counting to manage memory, incrementing and decrementing reference counts as needed.
  • A cyclic garbage collector handles objects with circular references.
  • Python also provides tools like context managers and the “with” statement to release resources automatically.
  • Python’s memory management simplifies coding by handling memory allocation and deallocation automatically.

To become a professional business analyst, check out Intellipaat’s Business Analyst Certification Course in Bangalore taught by industry experts.

22. What is PYTHONPATH?

PYTHONPATH serves as an environment variable within the Python programming language, empowering users to define supplementary directories for Python to search when seeking modules and packages. This variable serves as a search path and helps Python locate the necessary files to import when executing code. By setting the PYTHONPATH variable, users can extend the default search path and customize the module search behavior according to their needs. This feature enables developers to organize and structure their Python projects efficiently, facilitating easier module importation and enhancing code reusability.

23. What is the difference between modules and libraries?

In Python, modules are like standalone files that house specific code components, such as functions and variables. On the other hand, libraries are essentially vast collections of modules, and they come with pre-built functions and tools tailored for specific tasks or domains. These libraries not only simplify the development process but also enhance Python’s capabilities by providing readily available solutions for various programming challenges.

24. What are Python namespaces?

A Python namespace ensures that the names assigned to objects within a program are unique and can be used without conflict. In Python, namespaces are implemented as dictionaries where the object’s name serves as the key and the object itself serves as the value.

Let’s examine some examples of namespaces:

  • The Local Namespace is specific to a function and contains the names defined within that function. It is created temporarily when the function is called and is cleared once the function finishes executing.
  • The Global Namespace includes names from imported modules or packages that are used in the current project. It is created when the package is imported into the script and remains accessible throughout the script’s execution.
  • The Built-in Namespace comprises the built-in functions provided by Python’s core, as well as specific names dedicated to various types of exceptions.

Want to become a master in Python programming? Check out this Python Training for Data Science and excel in your Python career!

25. Explain Inheritance and its types in Python with an example?

Python embraces the principles of object-oriented programming and allows classes to acquire the characteristics of another class, a concept known as inheritance. This facilitates code reuse, promoting efficiency. The original class from which properties are inherited is referred to as the superclass or parent class, while the class inheriting those properties is known as the derived or child class. Python supports various types of inheritance, including the following:

Inheritance in Python

  • Multiple Inheritance: Python supports multiple inheritance, enabling a derived class to inherit attributes and methods from multiple parent classes, facilitating code reuse, and enhancing flexibility.
  • Multilevel Inheritance: With multilevel inheritance, a derived class inherits properties and methods from a parent class, which in turn inherits from another parent class, establishing a hierarchical relationship between classes.
  • Hierarchical Inheritance: In hierarchical inheritance, multiple classes inherit properties and methods from a common superclass, resulting in a tree-like structure where each derived class has its own specialized functionality.
  • Single Inheritance: In Python, single inheritance allows a derived class to inherit properties and methods from a single superclass, promoting code reuse and organizational structure.
  • Hybrid Inheritance: Hybrid inheritance combines different types of inheritance, such as single, multiple, or multilevel inheritance, to create complex class hierarchies that fulfill specific programming requirements, ensuring maximum code reuse and flexibility.

Know the difference between Functional Programming and Object Oriented Programming

26. What is __init__ in Python?

In Python classes, the reserved method init serves a similar purpose as constructors in object-oriented programming (OOP) terminology. When a new object is created, the init method is automatically called, initializing the object and allocating memory for it. This method can also be utilized to set initial values for variables.

Below is an example:

class Human:
    def __init__(self, age):
        self.age = age
    def say(self):
        print('Hello, my age is', self.age)
h = Human(22)


Hello, my age is 22

27. What is the difference between Python Arrays and Lists?

Criteria Python Arrays  Python Lists
Definition Arrays are data structures that hold fixed-size elements of the same type. Lists are versatile data structures that can hold elements of different types and sizes.
Mutable Arrays are mutable, meaning their elements can be modified once created. Lists are mutable, allowing for modification of elements after creation.
Size Array size is fixed upon creation and cannot be changed. Lists can dynamically resize to accommodate new elements or remove existing elements.
Homogeneous Arrays store elements of the same data type, ensuring homogeneity. Lists can store elements of different data types, allowing heterogeneity.
Access Elements in an array can be accessed using indexing. Elements in a list can be accessed using indexing.
Operations Arrays support mathematical and logical operations on their elements efficiently. Lists provide a wide range of built-in methods and operations for manipulation and data handling.
Memory Arrays consume less memory compared to lists. Lists consume more memory due to their flexibility and dynamic resizing.

Watch this Video on Python for Data Science Tutorial

28. How to install Python on Windows and set a path variable?

To install Python on Windows and set a path variable, follow the steps below:

Download Python:

  • Visit the official Python website at www.python.org.
  • Click on the “Downloads” tab.
  • Choose the latest version of Python for Windows.
  • Select the appropriate installer based on your system (32-bit or 64-bit).

Run the Installer:

  • Double-click the downloaded installer.
  • Check the box stating “Add Python to PATH” during the installation process.
  • Click on the “Customize installation” option if you want to customize the installation location or components.

Set the Path Variable:

  • After opening the Start menu, search “Environment Variables” or “Edit the system environment variables.”
  • Click on the “Environment Variables” button.
  • Find the “Path” variable in “System Variables” and click “Edit.”
  • Select “New” and then provide the path to your Python installation directory. It is typically found at “C:PythonXX” (XX represents the Python version number).
  • Click “OK” to save the changes.

Verify the Installation:

  • Open a new Command Prompt window.
  • Type “python” and press Enter.
  • If Python is installed correctly, you will see the Python interpreter prompt with the version information.

Here’s the code to check the Python version using Command Prompt:

python –version

29. Why do we need NumPy in Python?

NumPy is a core Python library for efficient numerical computing. It offers high-performance multidimensional array objects and tools for working with these arrays. Leveraging C for speed, it allows for vectorized operations, broadcasting, and direct array arithmetic, which boosts performance and reduces code complexity. Integral to Python’s scientific stack, it enables seamless integration with libraries like Pandas and Matplotlib. NumPy is memory-efficient, and provides extensive mathematical functionality, and its arrays form the basis of most Python-based data science applications. Its indispensability lies in its ability to handle large data sets with speed and precision.

30. Is this statement true “Python is a case-sensitive language”?

Yes, Python is a case-sensitive language. In Python, it is important to note that “Function” and “function” are distinct entities, similar to how SQL and Pascal handle them differently.


31. Difference between loc and iloc?

loc and iloc are two functions provided by the Pandas library in Python to access different parts of a DataFrame. They are primarily used for selecting rows and columns.

Aspect loc iloc
Type of Indexing Label-based Integer position-based
Input Accepts labels of rows and columns. Accepts integer positions for rows and columns
Slicing End label is inclusive in the range End position is exclusive in the range
Subsetting Can select rows with a particular label and condition Can select rows by integer locations regardless of the DataFrame index
Mixed Selection Allows using labels for both rows and columns Uses integer positions for both rows and columns
Callable Supports callable functions Also supports callable functions

32. What do you understand by iterators in Python?

Python iterators are objects that allow you to access elements of a collection one at a time. They use the __iter__() and __next__() methods to retrieve the next element until there are no more. Iterators are commonly used in for loops and can be created for custom objects. They promote efficient memory usage and enable lazy evaluation of elements. In summary, iterators provide a convenient way to iterate over data structures in a controlled and efficient manner.

33. Do we need to declare variables with respective data types in Python?

No. Python is a dynamically typed language, i.e., the Python Interpreter automatically identifies the data type of a variable based on the type of value assigned.

Want to know How to Become a Python Developer? Check out this blog to know the complete process.

34. What do you know about Dict and List Comprehension?

Python Comprehensions are like decorators that help to build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or a set. Comprehension is a powerful feature in Python that offers a convenient way to create lists, dictionaries, and sets with concise expressions. It eliminates the need for explicit loops, which can help reduce code size and save time during development.

Comprehensions are beneficial in the following scenarios:

  • Performing mathematical operations on the entire list
  • Performing conditional filtering operations on the entire list
  • Combining multiple lists into one
  • Flattening a multi-dimensional list

For example:

my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list]    # list comprehension

# output => [4 , 9 , 25 , 49 , 121]

squared_dict = {x:x**2 for x in my_list}    # dict comprehension

# output =>{11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}



35. What is the method to write comments in Python?

Python comments are statements used by the programmer to increase the readability of the code. With the help of the #, you can define a single comment. Another way of commenting is to use the docstrings (strings enclosed within triple quotes).
For example:

#Comments in Python 
print("Comments in Python ")

Master Python by taking up this online Python Course in Bangalore!!

36. Is multiple inheritance supported in Python?

Yes, unlike Java, Python provides users with a range of support in terms of inheritance and its usage. Multiple inheritance refers to a scenario where a class is instantiated from more than one individual parent class. This provides a lot of functionality and advantages to users.

37. What is the difference between range & xrange?

Functions in Python, range() and xrange(), are used to iterate inside a for loop for a fixed number of times. Functionality-wise, both these functions are the same. The difference comes when talking about the Python version support for these functions and their return values.

range() Method xrange() Method
In Python 3, xrange() is not supported; instead, the range() function is used to iterate inside for loops. The xrange() function is used in Python 2 to iterate inside for loops.
It returns a list. It returns a generator object as it doesn’t really generate a static list at the runtime.
It takes more memory as it keeps the entire list of iterating numbers in memory. It takes less memory as it keeps only one number at a time in memory.

38. What do you understand by the word Tkinter?

Tkinter is a built-in Python module that is used to create GUI applications and it is Python’s standard toolkit for GUI development. Tkinter comes pre-loaded with Python so there is no separate installation needed. You can start using it by importing it into your script.

39. Is Python fully object-oriented?

Python follows an object-oriented programming paradigm and has all the basic OOPs concepts, such as inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data member with two underscores.

40. Differentiate between NumPy and SciPy?

NumPy SciPy
NumPy stands for Numerical Python SciPy stands for Scientific Python
It is used for efficient and general numeric computations on numerical data saved in arrays. E.g., sorting, indexing, reshaping, and more This module is a collection of tools in Python used to perform operations such as integration, differentiation, and more
There are some linear algebraic functions available in this module, but they are not full-fledged Full-fledged algebraic functions are available in SciPy for algebraic computations

41. Explain all file processing modes supported in Python?

Python has various file-processing modes.

For opening files, there are three modes:

  • read-only mode (r)
  • write-only mode (w)
  • read–write mode (rw)

For opening a text file using the above modes, we will have to append ‘t’ with them as follows:

  • read-only mode (rt)
  • write-only mode (wt)
  • read–write mode (rwt)

Similarly, a binary file can be opened by appending ‘b’ with them as follows:

  • read-only mode (rb)
  • write-only mode (wb)
  • read–write mode (rwb)

To append the content in the files, we can use the append mode (a):

  • For text files, the mode would be ‘at’
  • For binary files, it would be ‘ab’

42. What do file-related modules in Python do? Can you name some file-related modules in Python?

Python comes with some file-related modules that have functions to manipulate text files and binary files in a file system. These modules can be used to create text or binary files, update content by carrying out operations like copy, delete, and more.

Some file-related modules are os, os.path, and shutil.os. The os.path module has functions to access the file system, while the shutil.os module can be used to copy or delete files.

Know about Python developer roles and responsibilities to begin a career as a Python developer.

43. Explain the use of the 'with' statement and its syntax?

In Python, using the ‘with’ statement, we can open a file and close it as soon as the block of code, where ‘with’ is used, exits. In this way, we can opt for not using the close() method.

with open("filename", "mode") as file_var:

44. Write a code to display the contents of a file in reverse?

To display the contents of a file in reverse, the following code can be used:

filename = "filename.txt"
with open(filename, "r") as file:
    lines = file.readlines()

for line in reversed(lines):

Now in these questions lets look at some python interview coding questions

45. Which one of the following statements is not valid?

  1. xyz = 1,000,000
  2. x y z = 1000 2000 3000
  3. x,y,z = 1000, 2000, 3000
  4. x_y_z = 1,000,000

The second statement is invalid. This is invalid because variable names in Python cannot contain spaces, and multiple variables cannot be assigned in this way without commas to separate them. Additionally, the values to be assigned are not separated by commas, making the statement syntactically incorrect.

46. Write a command to open the file c:\hello.txt for writing?


f= open(“hello.txt”, “wt”)

47. What does len() do?

len() is an inbuilt function used to calculate the length of sequences like list, python string, and array.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)

48. What does *args and **kwargs mean in Python?

  • .*args: It is used to pass multiple arguments in a function.
  • **kwargs: It is used to pass multiple keyworded arguments in a function in Python.

Want to know about the real-world uses of Python? Read our detailed blog on Python Project ideas now.

49. How will you remove duplicate elements from a list?

To remove duplicate elements from the list, we use the set() function.

Consider the below example:

demo_list = [5, 4, 4, 6, 8, 12, 12, 1, 5]
unique_list = list(set(demo_list))
output = [1, 5, 6, 8, 12]

50. How to delete files in Python?

You need to import the OS Module and use os.remove() function for deleting a file in Python.
consider the code below:

import os

51. How will you read a random line in a file?

We can read a random line in a file using the random module.

For example:

import random
def read_random(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)

52. Write a Python program to count the total number of lines in a text file?

Refer to the code below to count the total number of lines in a text file-

def file_count(fname):
    with open(fname) as f:
        for i, _ in enumerate(f):
    return i + 1

print("Total number of lines in the text file:",

53. What would be the output if I ran the following code block?

list1 = [2, 33, 222, 14, 25]
  1. 14
  2. 33
  3. 25
  4. Error

Ans. output:14

In Python, negative indexing allows you to access elements from the end of the list. The index -1 represents the last element, -2 represents the second-to-last element, and so on.

In the given code, list1[-2] refers to the second-to-last element in the list list1, which is 14. Therefore, the output of the code will be 14.

54. What is the purpose of “is”, “not” and “in” operators?

Operators are referred to as special functions that take one or more values (operands) and produce a corresponding result.

  • is: returns the true value when both the operands are true  (Example: “x” is ‘x’)
  • not: returns the inverse of the boolean value based upon the operands (example:”1” returns “0” and vice-versa
  • in: helps to check if the element is present in a given Sequence or not

55. Explain the use of ternary operators in Python?

The ternary operator is the operator that is used to show conditional statements in Python. This consists of the boolean true or false values with a statement that has to be checked.


x , y=10,20
count = x if x < y else y [/code] Explanation: The expression count = x if x < y else y is evaluated as follows:

If the condition x < y is true, then the value of x is assigned to count. This means that if the value of x is less than the value of y, the count will be equal to x.

If the condition x < y is false, then the value of y is assigned to count. This means that if the value of x is not less than the value of y, the ecount will be equal to y.

56. What is the process for appending values to a Python array?

In Python, adding elements in an array can be easily done with the help of extend(), append(), and insert() functions.
Consider the following example:

x=arr.array('d', [11.1 , 2.1 ,3.1] )
print(x)   #[11.1,2.1,3.1,10.1]
print(x)  #[11.1,2.1,3.1,10.1,8.3,1.3,5.3]
print(x)        # [11.1,2.1,6.2,3.1,10.1,8.3,1.3,5.3]

57. What is the procedure for deleting values from a Python array?

Elements can be removed from a Python array by using pop() or remove() methods.

pop(): This function will return the removed element.

remove(): It will not return the removed element.

Consider the below example :

x=arr.array('d', [8.1, 2.4, 6.8, 1.1, 7.7, 1.2, 3.6])


1.1  # element popped at 3 rd  index
array('d', [ 2.4, 6.8, 7.7, 1.2])

Are you interested in learning Python from experts? Enroll in our online Python Course in Chennai today!

58. Write a code to sort a numerical list in Python?

The following code can be used to sort a numerical list in Python:

numbers = ["2", "5", "7", "8", "1"]
numbers = [int(i) for i in numbers]

59. How will you reverse a list in Python?

To reverse a list in Python, you can use the slicing technique. Here’s a brief explanation of the process:

Start with the original list that you want to reverse.

Use the slicing syntax [::-1] to create a new list that includes all elements from the original list in reverse order.

Assign the reversed list to a new variable or overwrite the original list with the reversed version.

original_list = [1, 2, 3, 4, 5]

reversed_list = original_list[::-1]


Python Interview Questions - Python Career

60. How will you remove the last object from a list in Python?

my_list = [1, 2, 3, 4, 5]

Here, −1 represents the last element of the list. Hence, the pop() function removes the last object (obj) from the list.

Get certified in Python from the top Python Course in Delhi now!

61. What is the method for generating random numbers in Python?

This is achieved by importing the random module. It is the module that is used to generate random numbers.


import random
random.random # returns the  floating point random number between the range of [0,1].

62. Explain how to convert a string to all lowercase?

To convert a string to all lowercase in Python, you can use the built-in lower() method. The lower() method is available for strings and returns a new string with all characters converted to lowercase.

For Example:


Learn the complete Python Training in Hyderabad in 24 hours!

63. What does polymorphism refer to in Python?

Polymorphism in Python is the ability of the code to take multiple forms. Let’s say, if the parent class has a method named XYZ then the child class can also have a method with the same name XYZ having its own variables and parameters.

64. Explain encapsulation in Python?

Encapsulation in Python refers to the process of wrapping up the variables and different functions into a single entity or capsule. The Python class is the best example of encapsulation in Python.

65. What benefits do NumPy arrays provide compared to (nested) Python lists?

Nested Lists:

  • Python lists are efficient, general-purpose containers that support efficient operations like insertion, appending, deletion, and concatenation.
  • The limitations of lists are that they don’t support “vectorized” operations like element-wise addition and multiplication, and the fact that they can contain objects of differing types means that Python must store the data type information for every element, and must execute type dispatching code when operating on each element.


  • NumPy is more efficient and more convenient, as you get a lot of vector and matrix operations for free, this helps avoid unnecessary work and complexity of the code. NumPy is also efficiently implemented when compared to nested lists.
  • NumPy array is faster and contains a lot of built-in functions, that will help in FFTs, convolutions, fast searching, linear algebra, basic statistics, histograms, etc.

Advanced Python Interview Questions for Experienced

66. What is functional programming? Does Python follow a functional programming style? If yes, list a few methods to implement functionally oriented programming in Python?

Functional programming is a coding style where the main source of logic in a program comes from functions.

Incorporating functional programming in our codes means writing pure functions.

Pure functions are functions that cause little or no changes outside the scope of the function. These changes are referred to as side effects. To reduce side effects, pure functions are used, which makes the code easy-to-follow, test, or debug.

Python follows a functional programming style. Following are some examples of functional programming in Python.

filter(): Filter lets us filter some values based on a conditional logic.
list(filter(lambda x:x>6,range(9))) [7, 8]

map(): Map applies a function to every element in an iterable.
list(map(lambda x:x**2,range(5))) [0, 1, 4, 9, 16, 25]

reduce(): Reduce repeatedly reduces a sequence pair-wise until it reaches a single value.

from functools import reduce >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) -13

67. Explain monkey patching in Python?

Monkey patching is the term used to denote modifications that are done to a class or a module during runtime. This can only be done as Python supports changes in the behavior of the program while it is being executed.

The following is an example, denoting monkey patching in Python:

# monkeyy.py
class X:
    def func(self):
        print("func() is being called")

The above module (monkeyy) is used to change the behavior of a function at runtime as shown below:

import monkeyy
def monkey_f(self):
    print("monkey_f() is being called")
# Replacing the address of "func" with "monkey_f"
monkeyy.X.func = monkey_f

obj = monkeyy.X()

# Calling the function "func" whose address was replaced with 
the function "monkey_f()"

68. Explain about generators in Python?

Generators in Python are special functions that can be used to create iterable objects. Unlike regular functions that return a value and then terminate, generators use the yield keyword to suspend execution temporarily and yield a value one at a time. This makes generators memory efficient, as they don’t generate the entire sequence of values upfront but rather generate values on-demand.

Generators are helpful when dealing with large datasets or when the complete sequence of values is not needed at once. They allow us to iterate over a potentially infinite sequence without consuming excessive memory.

69. Explain the difference between pickling and unpickling?

The Pickle module accepts the Python object, and converts it into a string representation and stores it into a file by using the dump function. This process is called pickling. On the other hand, the process of retrieving the original Python objects from the string representation is called unpickling.

Want to know about the real-world uses of Python? Read our detailed blog on Python Applications now.

70. What is the difference between %, /, // ?

In Python, %, /, and // are arithmetic operators with distinct functions:

  • The ‘ % ’ is the modulo operator, which returns the remainder of a division. For instance, 5 % 2 would return 1.
  • The ‘ / ’ is the division operator that performs floating-point division and returns a float. For example, 5 / 2 would return 2.5.
  • The ‘ // ’ is the floor division operator that performs division but rounds down the result to the nearest whole number. So 5 // 2 would return 2.

Python Interview Questions for 3 Years Experienced

71. What are decorators?

In Python, decorators serve as essential functions that enable the addition of functionality to an already existing function without altering its structure. These decorators are denoted by the @decorator_name syntax in Python and are invoked in a bottom-up manner. Below is an example illustrating how decorators work correctly:

def decorator_lowercase(function):   # defining a Python decorator
    def wrapper():
        result = function()
        result_lowercase = result.lower()
        return result_lowercase
    return wrapper
@decorator_lowercase ## calling the decorator
def intro():                     # Normal function
    return 'Hello, I AM SAM'


Output: ‘hello,i am sam’

72. What is scope resolution?

In Python, a scope defines the region of code where an object remains valid and accessible. Every object in Python operates within its designated scope. Namespaces are used to uniquely identify objects within a program, and each namespace is associated with a specific scope where objects can be used without any prefix. The scope of a variable determines its accessibility and lifespan.

Let’s explore the different scopes created during code execution:

  • Local scope: This refers to the objects that are defined within the current function and are accessible only within that function.
  • Global scope: Objects in the global scope are available throughout the execution of the code. 
  • Module-level scope: This scope encompasses global objects that are associated with the current module in the program. These objects are accessible within the module.
  • Outermost scope: This refers to all the built-in names that can be called from anywhere in the program.

Interested in learning React JS? Click here to learn more about this React JS Certification!

73. How can you shuffle the elements of a list in Python?

This can be easily achieved by using the Shuffle() function from the random library, as shown below:

from random import shuffle
import random


my_list = [1, 2, 3, 4, 5]

This code will randomly reorder the elements in my_list.

74. Describe the split(), sub(), and subn() methods found within Python's 're' module?

These methods belong to the Python RegEx or ‘re’ module and are used to modify strings.

  • split(): This method is used to split a given string into a list.
  • sub(): This method is used to find a substring where a regex pattern matches, and then it replaces the matched substring with a different string.
  • subn(): This method is similar to the sub() method, but it returns the new string, along with the number of replacements.

Learn more about Python from this Python Training in Pune to get ahead in your career!

75. What is a map function in Python?

The map() function in Python has two parameters, function and iterable. The map() function is a powerful tool that allows you to apply a specified function to every element within an iterable. It takes two arguments: the function you want to apply and the iterable containing the elements you want to process. This function is a versatile way to perform operations on multiple items simultaneously, making your code more efficient and concise

For example:

def calculateSq(n):
return n*n
numbers = (2, 3, 4, 5)
result = map( calculateSq, numbers)

Interested in learning Python? Check out this Python Course in Mumbai!

76. Why doesn't Python deallocate all memory upon exit?

  • Whenever Python exits, especially those Python modules, which are having circular references to other objects or the objects that are referenced from the global namespaces, the memory is not always de-allocated or freed.
  • It is not possible to de-allocate those portions of memory that are reserved by the C library.
  • On exit, because of having its own efficient clean-up mechanism, Python will try to de-allocate every object.

77. Can you write an efficient code to count the number of capital letters in a file?

The normal solution for this problem statement would be as follows:

with open(SOME_LARGE_FILE) as countletter:

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

To make this code more efficient the whole code block can be converted into a one-line code using the feature called generator expression. With this, the equivalent code line of the above code block would be as follows:

count = sum(1 for line in countletter for character in line if character.isupper())

Python Interview Questions for 5 Years Experienced

78. How does Python Flask handle database requests?

Flask supports a database-powered application (RDBS). Such a system requires creating a schema, which needs piping the schema.sql file into the sqlite3 command. Python developers need to install the sqlite3 command to create or initiate the database in Flask.

Flask allows to request for a database in three ways:

  • before_request(): They are called before a request and pass no arguments.
  • after_request(): They are called after a request and pass the response that will be sent to the client.
  • teardown_request(): They are called in a situation when an exception is raised and responses are not guaranteed. They are called after the response has been constructed. They are not allowed to modify the request, and their values are ignored.

Sign up for the Full Stack Developer Course to begin your career journey today.

79. What is a docstring in Python?

Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python. Rather than being completely ignored by the Python interpreter, like in the case of comments, these are defined within triple quotes.


Using docstring as a comment.
This code add two numbers

80. What is regression?

Regression is termed as a supervised machine learning algorithm technique, which is used to find the correlation between variables. It helps predict the value of the dependent variable (y) based on the independent variable (x). It is mainly used for prediction, time series modeling, forecasting, and determining the causal-effect relationship between variables.

Scikit library is used in Python to implement the regression and all machine learning algorithms.

There are two different types of regression algorithms in machine learning :

Linear Regression: Used when the variables are continuous and numeric in nature

Logistic Regression: Used when the variables are continuous and categorical in nature

81. What is classification?

Classification refers to a predictive modeling process where a class label is predicted for a given example of input data. It helps categorize the provided input into a label that other observations with similar features have. For example, it can be used for classifying a mail whether it is spam or not, or for checking whether users will churn or not based on their behavior.

These are some of the classification algorithms used in Machine Learning:

82. Write a program in Python to execute the Bubble sort algorithm?

Check out the code below to execute bubble sort-

def bubbleSort(x):
    n = len(x)
    # Traverse through all array elements
    for i in range(n-1):
        for j in range(0, n-i-1):
            if x[j] > x[j+1]:
                x[j], x[j+1] = x[j+1], x[j]

# Driver code to test above
arr = [25, 34, 47, 21, 22, 11, 37]

print("Sorted array is:")
for i in range(len(arr)):



83. Create a Python sorting algorithm for a dataset of numbers?

code to sort a list in Python:

my_list = ["8", "4", "3", "6", "2"]

my_list = [int(i) for i in list]


print (my_list)



84. Write a Program to print ASCII Value of a character in Python?

Check the below code to print the ASCII value:

x= 'a'

# print the ASCII value of the assigned character stored in x

print(" ASCII value of '" + x + "' is", ord(x))

Output: 65

85. What is the lambda function in Python?

A Python lambda function is an anonymous function (a function that does not have a name). To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.

For example:

l = lambda x,y : x*y
print(a(5, 6))


Any more queries? Feel free to share all your doubts with us in our Python Community and get them clarified today!

86. What does 'self' mean in Python?

Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.

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


Class A:
    def func(self):

87. What is the difference between append() and extend() methods?

Both append() and extend() methods are used to add elements at the end of a list.

The primary differentiation between the append() and extend() methods in Python is that append() is used to add a single element to the end of a list. In contrast, open () is used to append multiple aspects, such as another list or an iterable, to the end of a list.

For in-depth knowledge, check out our Python Tutorial and boost your Python skills!

88. How is multi-threading achieved in Python?

Python has a multi-threading package but, it is commonly not considered a good practice to use it as it results in increased code execution time.

  • Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time. The process makes sure that a thread acquires the GIL, does work, and then passes the GIL onto the next thread.
  • This occurs almost instantaneously, giving the illusion of parallel execution to the human observer. However, the threads execute sequentially, taking turns utilizing the same CPU core.

89. Which one of the following is not the correct syntax for creating a set in Python?

  1. set([[1,2],[3,4],[4,5]])
  2. set([1,2,2,3,4,5])
  3. {1,2,3,4}
  4. set((1,2,3,4))



Explanation: The argument given for the set must be iterable.

90. What is the difference between / and // operators in Python?

/: is a division operator and returns the value of the quotient.

  • 10/3
  • 3.33

//: is known as the floor division operator and is used to return the value of the quotient before the decimal point.

  • 10//3
  • 3

91. What is Pandas?

Pandas is an open-source Python library , which supports data structures for data-based operations associated with data analyzing and data manipulation. Pandas, with its rich sets of features, fits in every role of data operation, whether it be related to implementing different algorithms or solving complex business problems. Pandas helps to deal with a number of files in performing certain operations on the data stored by files.

92. What are DataFrames?

A dataframe refers to a two dimensional mutable data structure or data aligned in a tabular form with labeled axes(rows and column).


pandas.DataFrame( data, index, columns, dtype)
  • data: It refers to various forms like ndarray, series, map, lists, dict, constants and can take other DataFrame as Input.
  • Index: This argument is optional as the index for row labels will be automatically taken care of by Pandas library.
  • columns: This argument is optional as the index for column labels will be automatically taken care of by the Pandas library.
  • dtype: It refers to the data type of each column.

93. What is the difference between DataFrames and Series?

A Series is a one-dimensional array-like object in pandas that can hold any data type, while a DataFrame is a two-dimensional, table-like structure with potentially heterogeneously-typed columns. You can think of a DataFrame as a collection of Series objects that share the same index.

94. What is the process for merging DataFrames in Pandas?

Different DataFrames can be easily combined with the help of functions listed below:

Append(): This function is used for the horizontal stacking of DataFrames.

  • concat(): This function is used for vertical stacking and is best suited when the DataFrames to be combined possess the same column and similar fields.
pd.concat([data_frame1, data_frame2])
  • join(): This function is used to extract data from different DataFrames, which have one or more columns in common.

95. How do you split the data in train and test dataset in Python?

This can be achieved by using the scikit machine learning  library and importing train_test_split function in Python as shown below:

from sklearn.model_selection import train_test_split

# test size = 30% and train = 70%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

96. Why is a set known as unordered? Is it mutable or immutable?

A set is called “unordered” because the items in a set don’t have a specific order or sequence like a list does. It’s more like a collection of items, and you can’t access them by their position.

Sets in Python are mutable, which means you can add or remove items from a set after it’s created. However, the items within the set (the elements) are themselves immutable, meaning they cannot be changed. You can add or remove elements from a set, but you can’t modify the elements themselves once they’re in the set.

97. Explain the difference between percentile and quantiles in Python?

In Python, percentiles and quantiles are related but different concepts.

Percentiles divide a dataset into 100 equal parts, allowing you to understand the relative position of a value within the entire dataset. For example, the 25th percentile corresponds to the value below which 25% of the data falls.

Quantiles, on the other hand, divide the dataset into any number of equal parts, such as quartiles (four parts) or quintiles (five parts). They offer a more flexible way to segment the data for analysis.

98. What is SVM?

Support vector machine (SVM) is a supervised machine learning model that considers the classification algorithms for two-group classification problems. Support vector machine is a representation of the training data as points in space are separated into categories with the help of a Support Vector Machine (SVM) is a supervised machine learning model for classifying data into two groups. It is particularly suitable for binary classification problems. SVM represents the training data as points in space and aims to separate them into distinct categories. The separation is achieved by identifying a clear gap between the data points, and the SVM model strives to maximize the width of this gap.

Want to become a Machine Learning expert? Enroll in our Machine Learning Certification Today!

99. Write a program in Python to produce Star triangle?

The below code produces a star triangle-

def Star_triangle(n):
    for x in range(n):
        print(' '*(n-x-1)+'*'*(2*x+1))




Learn how to calculate the Fibonacci Series in C with this easy-to-follow blog!

100. Write a program to produce Fibonacci series in Python?

The Fibonacci series refers to a series where an element is the sum of two elements prior to it.

n = int(input(“number of terms? “))
n1, n2 = 0, 1
count = 0

if n <= 0: print("Please enter a positive integer") elseif n == 1: print("Fibonacci sequence upto", n, ":") print(n1) else: print("Fibonacci sequence:") while count < n: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1 [/code]

101. Write a program in Python to check if a number is prime?

The below code is used to check if a number is prime or not

num = 13

if num > 1:
    for i in range(2, int(num/2)+1):
        if (num % i) == 0:
            print(num, "is not a prime number")
        print(num, "is a prime number")
    print(num, "is not a prime number")


13 is a prime number

Python OOPs Interview Questions

102. What are classes and objects?

A class is a blueprint for creating objects. It contains member functions, attributes, etc. that get instantiated when the object is called.

On the other hand, an object is nothing but an instance of a class, possessing state, identity, and functionality, and is used to call class members.
Let’s take a look at a simple example:
Here, we will create a class named office using Python

class Office:
def __init__(self): 
print("class is created")

def sample(self):
self.employee = "ramesh"

Now we will create an object for the class Office.
#Object is created
obj = Office()
#using object to call member functions and their attributes

Here the output shows the creation of a class in Python, and using an object to call member functions and their attributes.
class is created

103. What is abstraction?

One of the pillars of object-oriented programming is abstraction. Abstraction is a very simple process where only the necessary details are shown and the background computations or processes stay hidden. To simplify, let’s try to understand abstraction with an example:

Let’s say you visit a motor showroom to buy your new car. The dealer will take you for a quick ride to show you the features of the car.

The noticeable thing here is that you will be shown the entire car, but you will not be able to figure out how the actual combustion and other necessary details to move the car are working. And this is exactly how abstraction works: only the necessary details are shown, and internal functionality is hidden from the users.

104. What are constructors?

Constructors are called when an object is created for a class. Constructors are used to instantiate the objects and assign values to them. Let’s take a look at a simple example:

class Office:
def __init__(self): 
print("class is created")

#Object is created
obj = Office()

As soon as the object is created, the constructor is called, and the output shows “class is created.” Similarly, we can use constructors like list(), int() to instantiate and assign values to them.

105. Write a program to depict inheritance and its types in Python?

Let’s take a look at a simple example in Python to understand inheritance and its types:

#single inheritance
class Animals:
def House(self):
print("lives in Jungle")

class Snakes(Animals):
def eats(self):
print("eats insects")

obj = Snakes()
lives in Jungle
eats insects

#multiple inheritance
class Maths:
def Marks(self): 
self.maths = 90

class English:
def Marks(self):
self.english = 85

class Result(Maths, English):
def __init__(self):

def result(self):
self.res = (self.maths + self.english) // 2
print("The result is : {}%".format(self.res))

obj = Result()

The result is : 87%

#multi-level inheritance
class Vehicle:
def __init__(self):
self.Type = "Commercial"
print("Vehicle Type : {}".format(self.Type))

class Name(Vehicle):
def __init__(self):
self.Name = "Ashok Leyland"
print("Vehicle Name: ".format(self.Name))

class Final(Name):
def __init__(self):
self.Tyres = 8
print("Number of tyres is: {}".format(self.Tyres))

obj = Final()


Vehicle Name:
Vehicle Type : Commercial
Number of tyres is: 8

Python Pandas Interview Questions

106. What are some of the string operations that can be performed using Pandas in Python?

There are various operations you can perform using Pandas in Python. Some of the examples are as follows:

  1. Making all the strings uppercase
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to uppercase letters




1        VIRAT KOHLI



4           KL RAHUL

dtype: object

  1. Making all the strings lowercase
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to lowercase letters



0       rohit sharma

1        virat kohli

2       shubman gill

3    ravindra jadeja

4           kl rahul

dtype: object
  1. Check whether the string starts with a pattern
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to uppercase letters



0     True

1    False

2    False

3     True

4    False

dtype: bool

  1. Splitting the strings
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to uppercase letters

sample.str.split(" ")


0       [Rohit, Sharma]

1        [Virat, Kohli]

2       [Shubman, Gill]

3    [Ravindra, Jadeja]

4           [KL, Rahul]

dtype: object

  1. Finding the string
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to uppercase letters



0    0

1   -1

2   -1

3    0

4    3

dtype: int64

  1. Stripping the whitespaces in the string
import pandas as pd

sample = pd.Series([' Rohit Sharma ',

                    ' Virat Kohli  ',

                    ' Shubman Gill    ',

                    '   Ravindra Jadeja  ',

                    '     KL Rahul '])

#make all strings to uppercase letters



0       Rohit Sharma

1        Virat Kohli

2       Shubman Gill

3    Ravindra Jadeja

4           KL Rahul

dtype: object

  1. Replacing a string with another
import pandas as pd

sample = pd.Series(['Rohit Sharma',

                    'Virat Kohli',

                    'Shubman Gill',

                    'Ravindra Jadeja',

                    'KL Rahul'])

#make all strings to uppercase letters

sample.str.replace('Shubman Gill', 'Rishabh Pant')


0       Rohit Sharma

1        Virat Kohli

2       Rishabh Pant

3    Ravindra Jadeja

4           KL Rahul

dtype: object

107. How can you perform stacking operations on a Pandas DataFrame?

Stacking is used to reshape the DataFrames. Let’s take a look at a simple example:

sample = pd.DataFrame([[65, 158], [92, 183]],

                      index=['Ramesh', 'Suresh'],

                      columns=['weight', 'height'])



Ramesh  weight     65

height    158

Suresh   weight     92

height    183

dtype: int64

108. How do you remove the index from a Pandas DataFrame?

To remove the index from a dataframe, we can add a simple line of code as follows:

import pandas as pd

data = pd.DataFrame({"student_id": [29, 59, 72, 54],

                       "Name": ['sravan', 'jyothika',

                                'harsha', 'ramya'],})

data.index = data['student_id']

del data['student_id']



remove index from a Pandas dataframe

109. How do you create a dataframe, and what are some of the operations you can perform on Pandas DataFrames?

There are several ways to create a dataframe in Python, some of them are as follows:

  1. pd.DataFrame([['Ajay', 23], ['Neelam', 25], ['Anita', 42]], columns=['Name', 'Age'])


How to create Dataframe Operations


DataFrame({'Name': ['Ajay', 'Neelam', 'Anita'],

              'Age': [23,25,42]})

How to create Dataframe Operations - 2


DataFrame([{'Name': 'Ajay', 'Age': 23},

{'Name': 'Neelam', 'Age': 25},

{'Name': 'Anita', 'Age': 42}])

How to create Dataframe Operations - 3

Some of the operations that you can perform on the data frames are as follows:

  1. Manipulation
  2. Data imputation
  3. Merging operations
  4. Measures of central tendency
  5. Measures of kurtosis
  6. Measures of spread
  7. Visualizations

110. How do you create a series in Pandas in different ways?

A series in Pandas can be created in the following ways:

  1. Series(range(0,100, 10), index=[x for x in range(0,20, 2)])


0      0

2     10

4     20

6     30

8     40

10    50

12    60

14    70

16    80

18    90

dtype: int64

  1. x = [1,2,3,4,5]
y = ['One', 'Two', 'Three', 'Four', 'Five']

pd.Series(y, index = x)
[code language="python"]


1      One

2      Two

3    Three

4     Four

5     Five

dtype: object

  1. dictionary = {'One': 1, 'Two': 2, 'Three':3, 'Four':4, 'Five':5}



One      1

Two      2

Three    3

Four     4

Five     5

dtype: int64

Numpy Interview Questions

111. Create a Numpy array in the shape of 2x3 with random integers in the range 0-100. Reshape the array in the shape 3x2 and print the updated shape of the resultant array?

import numpy as np

arr1= np.random.randint(0,101, (2,3))


newarr1= arr1.reshape(3,2)



[[35 61 24]

[20 38 31]]

(3, 2)

112. Create an array that will have days from an entire year in the datetime format using the datetime64 Numpy method?

from datetime import datetime

import random

darr = np.arange('2024-01-01', '2025-01-01',dtype='datetime64')


The print statement will give us the desired output.

113. For the given two arrays A and B, find the correlation coefficients?

A = np.array([[11,17,42],[21,19,27]])

B = np.array([[12,44,39],[62,81,10]])

A = np.array([[11,17,42],[21,19,27]])

B = np.array([[12,44,39],[62,81,10]])

corr= np.corrcoef(A,B)



[[ 1.          0.9106039   0.53232532 -0.90264562]

[ 0.9106039   1.          0.13487934 -0.99982205]

[ 0.53232532  0.13487934  1.         -0.11616343]

[-0.90264562 -0.99982205 -0.11616343  1.        ]]

114. Given an array A, perform the following operations?

A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15], [16,17,18]])

  1. Horizontal split
  2. Vertical Split
  3. Row Split
  4. Column Split
A = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15], [16,17,18]])

Horizontal split

ha= np.hsplit(A,3)



[array([[ 1],

[ 4],

[ 7],



[16]]), array([[ 2],

[ 5],

[ 8],



[17]]), array([[ 3],

[ 6],

[ 9],




Vertical split

va= np.vsplit(A,6) #or can also do A,3 ; A,2



[array([[1, 2, 3]]), array([[4, 5, 6]]), array([[7, 8, 9]]), array([[10, 11, 12]]), array([[13, 14, 15]]), array([[16, 17, 18]])]

Row Split

ra= A[0 , : ]



[1 2 3]

Column Split

ca= A[: , 0]



[ 1  4  7 10 13 16]

115. For the given two arrays A and B. a = np.array([[2,9],[6,13]]) b = np.array([[1,4],[3,11]]) Perform the following operations: a. Cross product of A and B. b. Dot product of A and B. c. Matrix multiplication of A and B. d. Square root of A and B?

a = np.array([[2,9],[6,13]])

b = np.array([[1,4],[3,11]])

Cross Product




[-1 27]

Dot Product

dot = np.dot(a,b)



[[ 29 107]

[ 45 167]]

Matrix multiplication

m_multi= np.multiply(a,b)



[[  2  36]

[ 18 143]]

Square root

sq_a= np.sqrt(a)



[[1.41421356 3.        ]

[2.44948974 3.60555128]]

Python Libraries Interview Questions

116. What is Matplotlib, and how and why do you use it using Python?

Matplotlib is a powerful open-source data visualization library in Python that helps us create static and interactive plots. This library gives us some of the simplest functions to create a plot. Different types of plots are provided, including bar plots, line plots, area plots, box plots, scatter plots, etc.

Let’s see how to use this library with an example of creating a bar plot.

Step 1: Matplotlib library in Python needs to be imported before use. We can install this library with the help of pip, which is a package management system.

pip install

Step 2: We need to import the library

pip install step 2

Step 3: Collect data that you want to visualize. This data can be in the form of a list, tuple, dataframe, etc.pip install step 3

Step 4: Visualizing the bar plot in the simplest way. We can further customize it to make it look better.

pip install step 4

Uses of Matplotlib:

  • Matplotlib is open-source.
  • Provides simple functions to visualize
  • Supports different forms of data
  • Gives high-quality images in different formats.
  • Can run on different platforms

117. How do you use Scipy, and what are some of the operations you can perform using Python?

SciPy in Python refers to Scientific Python. It is an open-source library built on NumPy to perform signal processing, numerical operations, linear algebra, and more. SciPy has more features when it comes to computations compared to NumPy. Some of the sub-packages in SciPy include: scipy.special, scipy.signal, scipy.stats, scipy.linalg etc.

How to use SciPy:

Step1: Install the library

pip install scipy

Step 2: Import the library

import scipy

Step 3: Using the library. We have different sub-packages in SciPy, as mentioned above, so let’s discuss some of them below.


  • Contains advanced mathematical functions, like gamma, square root, elliptic functions etc.
  • Below is the code for the gamma function in scipy.special.

pip scipy code 1


  • Used to provide a wide range of statistical operations to analyze the data.
  • Below is the code to extract 5 random samples from a normal distribution.

pip scipy code 2


  • Used in signal processing tasks.
  • Below is the code for creating hamming-type windows, which are used for filter design and spectral analysis.

pip scipy code 3


  • Used for advanced linear algebra tasks.
  • Below is the code to find the eigenvalues and vectors of a matrix.

pip scipy code 4

Above are some of the many operations we have in the Scipy library.

118. Plotly is one of the most popular Python libraries. Give an example using Python?

Plotly is a Python library well known for its interactive plots. Just like other libraries, Plotly also provides a large variety of plots. Let’s look at the example below:

Step 1: Import necessary libraries like graph objects from the Plotly library and Numpy

plotly code 1

Step 2: Gather data necessary for plotting the graph.

plotly code 2

Step 3: Specify the kind of plot. In our case, it’s the scatter plot.

plotly code 3

Step 4: Specify a title and labels for the x and y axis.

plotly code 4

Step 5: Combining trace and layout to create a figure.

plotly code 5

119. Which library would you use to perform linear algebra operations using Python?

The NumPy library offers a package – numpy.linalg that can be used to perform linear algebra operations using Python.
Here is a simple example to show how you can use it:

import numpy
a = numpy.array([[1, 2], [2, 6]])


Python Interview Questions for Data Science

120. Why would you use NumPy arrays instead of lists in Python?

NumPy arrays provide users with three main advantages, as shown below:

  • NumPy arrays consume a lot less memory, thereby making the code more efficient.
  • NumPy arrays execute faster and do not add heavy processing to the runtime.
  • NumPy has a highly readable syntax, making it easy and convenient for programmers.

121. How can you use Python libraries for web scraping?

Web scraping is a process where we visit a webpage and scrape the desired data from the webpage in a format that can be a .json format and analyze or use it according to our requirements. The Python libraries that prove to be a very good addition to the tally in terms of web scraping are Beautiful Soup, Scrapy, Requests, etc.

122. How do you identify missing values and deal with missing values in Dataframe?


isnull() and isna() functions are used to identify the missing values in your data loaded into dataframe.


Handling missing Values:

There are two ways of handling the missing values :

Replace the  missing values with 0


Replace the missing values with the mean value of that column

df[‘col_name’] = df[‘col_name’].fillna((df[‘col_name’].mean()))

Python Coding Interview Questions

123. Create a palindrome checker using Python. Using item assignment to an empty array?

string = 'madame'
res = []
def checker(x):
res = x[::-1]
if res == x:

print("not a palindrome")

not a palindrome

124. Write a Python program that will print the length of an array without using the len() function?

a = [1,2,3,4,5]
count = 0
for i in a:
count = count + 1



Python Programming Interview Questions

125. Write a program to find the greatest of the two numbers?

We can get the indices of N maximum values from a NumPy array using the below code:

import numpy as np

ar = np.array([1, 3, 2, 4, 5, 6])


126. What is the easiest way to calculate percentiles when using Python?

The easiest and the most efficient way you can calculate percentiles in Python is to make use of NumPy arrays and its functions.
Consider the following example:

import numpy as np
a = np.array([1,2,3,4,5,6,7])
p = np.percentile(a, 50) #Returns the 50th percentile, which is also the median

127. Write a Python program to check whether a given string is a palindrome or not, without using an iterative method?

A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam, nurses run, etc.
Consider the below code:

def fun(string):
s1 = string
s = string[::-1]
if s1 == s:
return True
return False


Python Technical Interview Questions

128. Write a Python program to calculate the sum of a list of numbers?

def sum(num):
if len(num) == 1:
return num[0] # With only one element in the list, the sum result will be equal to the element.
return num[0] + sum(num[1:])

print(sum([2, 4, 5, 6, 7]))

129. Write a program to find the greatest of the two numbers?

x = 5
y = 10
print("x is greater") if x > y else print('Both are equal') if x == y else print('Y is greater')
Y is greater

x = 15
y = 5
print("x is greater") if x > y else print('Both are equal') if x == y else print('Y is greater')
x is greater

x = 15
y = 15
print("x is greater") if x > y else print('Both are equal') if x == y else print('Y is greater')

Both are equal

130. Write a Python program to check if the given input is an Armstrong number or not?

def armstrong(num):
sum = 0
temp = num
while temp > 0:
x = temp % 10
sum = sum + x**3
temp = temp // 10

print("armstrong") if sum == num else print("not an armstrong")



131. Create a Python program to depict list comprehension?

Here is a simple example of how to create a list using list comprehension.
[x**2 for x in range(0,100,10)]
[0, 100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]

132. Create a Python program that will depict dictionary comprehension in Python?

A simple example of how to create a dictionary using dictionary comprehension
{x: x**2 for x in range(0,100,10)}
{0: 0,
10: 100,
20: 400,
30: 900,
40: 1600,
50: 2500,
60: 3600,
70: 4900,
80: 6400,
90: 8100}

133. Write a Python program to show abstraction in Python?

from abc import ABC, abstractmethod

class A(ABC):
def sum(self):

class B(A):
def sum(self, a, b):
self.a = a
self.b = b
return self.a // self.b

obj = B()


Core Python Interview Questions

134. What is a regular expression, and how do you use it in Python?

The concept of regular expressions emerges with the need to optimize searching algorithms for strings. Match patterns called regular expressions are used to find or replace the matching patterns in strings while performing string operations.
Let’s take a look at a simple example to understand the usage of regular expressions:
import re

string = "Intellipaat is a fast growing global Ed-Tech brand"
x = re.search('\s', string) #first white space search


135. What are character classes in regular expressions?

The following are some of the character classes in regular expressions:
1. [abc] – Matching the alphabets i.e a b or c.
2. [a-z] [A-Z] – Matching the alphabets both lowercase and uppercase, in the range a to z.
3. [0-9] – matching the letters in the range specified.
4. [a-zA-Z0-9] – To match any alphanumeric character.
5. [^abc] – Match anything but a b or c.

136. How do you use multi-line comments in Python?

To use multi-line comments, we can use a very simple approach shown below:
this is a
multi line
print(“Multi line comment above”)

137. What is exception handling? How do you handle exceptions in Python?

In programming languages, there are two terminologies, i.e., errors and exceptions. Errors, on the other hand, stop the execution of the program, like syntax errors, name errors, etc., but the exceptions change the normal flow of the program. So it becomes necessary to handle exceptions during the execution of the program, and that is known as exception handling.

Let’s take a look at a simple example to understand how you can handle exceptions using Python:
Here in a normal scenario, the program would throw an error, but we can handle the exception using the try-and-catch block.

x = 5
y = "10"
z = x + int(y)
except TypeError:
print("Error: cannot add an int and a str")


138. Write a Python program to print a pyramid asterisk pattern in Python?

n = 5
k = 0
for i in range(1, n+1):
for j in range(1, (n-i)+1):
print(end=" ")

while k!=(2*i-1):
print("*", end="")
k += 1

k = 0

Download the Python Interview Questions and Answers PDF to prepare for interviews offline.



Python programming envisions the landscape that will shape the greatest invention of the 21st century, i.e., Artificial Intelligence. With the growing demand for skilled professionals, Python programming will be the most in-demand skill in 2024. Join the revolution with our Python Course and stand out from the crowd with an enriching learning experience and career growth.

If you have any questions, reach out to us in the comments, or post your queries in the Intellipaat community space.

Course Schedule

Name Date Details
Python Course 01 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 08 Jun 2024(Sat-Sun) Weekend Batch
View Details
Python Course 15 Jun 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Technical Research Analyst - Deep Learning

As a Technical Research Analyst specializing in Deep Learning, Aditya combines expertise in Python with a keen interest in cutting-edge technologies. He possesses a year of experience in designing and deploying robust applications. Additionally, he is passionate about writing and conveying complex technical concepts with clarity and precision.