Top Python Interview Questions – All Time 2022 Updated

Python is a very important programming language nowadays and its significance is increasing day by day in multiple domains whether it is data science, data analytics, machine learning, data engineering, bioengineering, etc.

In this article, we will share a list of important questions and their answers which are asked in many interviews in MNCs (Wipro, TCS, Infosys, PWC, Deloitte, KPMG, Cognizant, etc.) for different job roles and you can refer to these questions irrespective of the job role you will be interviewed for.

These questions are memory-based compilation by asking about interview experiences of the candidates who appeared in interviews in different MNCs for different job roles like Python developer, backend developer, data scientist, data analyst, machine learning engineer, lead python developer, etc.

So, let’s start studying important python questions and their answers.

Python Interview Questions and Answers

Q1. What are the important features of Python?

Ans1. The 10 key features of Python are as follows:

  1. Free & open source
  2. Dynamically Typed Language
  3. Interpreted Language
  4. Open source
  5. Platform Independent
  6. Automated garbage collection
  7. Can be used with other languages like Java, C++, C, etc.
  8. Supports Graphical User Interface
  9. Large community support
  10. Supports functional, structural, and object-oriented programming

Q2. What are the different data types in Python?

Ans2. Python data types can be classified into the following categories.

Q3. What are .pyc files in python and how it is different from .py files?

Ans3. The .pyc file contains compiled bytecode of Python source files i.e., .py file. The .pyc files are loaded by the Python interpreter before loading the .py files in order to save some time by not re-compiling the Python source code every time.

Q4. What do you mean by slicing in Python?

Ans4. In Python, Slicing is a technique for accessing specific parts of sequences such as strings, tuples, and lists. It is used by mentioning the colon inside the square brackets and it separates the start index and end index such as [start_index : end_index]

For e.g., In order to access python from the below string we can use slicing as follows:

Python slicing
str ="Java Python C++"


Q5. What do you mean by negative indexing in Python?

Ans5. Negative indexing is used in Python for accessing the last items in the iterable using a slicing operation. For example, if we want to access the last items from the iterable we can access it using the -1 index, the second last using -2, and so on.

lst = [10, 20, 30, 40, 50]
print (lst[-1])
print (lst[-2])


Q6. What are decorators in Python?

Ans6. Decorators are used in Python for extending or modifying the behavior of existing functions or classes. This is also called metaprogramming as it changes or modifies another part of the program at compile time without actually modifying the original function or class.

The below example will help you understand the concept of decorators.

def capital(text):
    return text.upper()
new = capital

Q7. What are generators in Python?

Ans7. The generator is a special kind of function that does not return a single value instead it returns an iterator object having a sequence of values. In the generator function, the yield statement is used in place of the return statement.

The generator function has lazy execution i.e, produces results only when asked for.

The difference between yield and return statements is that yield while returning a value pauses the execution and maintains the internal states also whereas a return statement returns a value and terminates the execution of the function.

The following is an example of executing a simple generator function.

def custgenerator():
    print('First iteration')
    yield 15

    print('Second iteration')
    yield 25

    print('Last iteration')
    yield 35

In the above example, the custgenerator() is a generator function. It uses yield statement to return the value each time it is called. However, we need to create an iterator (next) for this function for producing the output.

Using for Loop with Generator Function

The generator function can be used with for loop also. The below program will help us understand how to call the generator function with for loop.

Example: Write a program to print the table of the given number using the generator.

def table(n):  
    for i in range(1,11):  
        yield n*i  
        i += 1 

# calling yield function inside for loop
for i in table(7):

Q8. Difference between map, reduce, and filter function in Python


The map is a function that works like list comprehensions and for loops. It is used when you need to map or implement functions on various elements at the same time.Filter is a similar operation, but it requires the function to look for a condition and then, only returns those elements from the collection that satisfy the condition. Reduce is an operation that breaks down the entire process into pair-wise operations and uses the result from each operation, with the successive element.
For example:
Using the Map function, create a list ‘cube’, which consists of the cube of numbers in input_list.
input_list =[5,6,4]
out_list =[25,216,64]

cube= list(map(lambda x:x**3,input_list))
For example:
Extract a list of names that start with an ‘s’ and end
with a ‘p’ (both ‘s’ and ‘p’
are lowercase) in input_list.

sp = list(filter(lambda x:x[0].lower()==’s’ and x[-1].lower()==’p’,input_list))
For example:
Using the Reduce function, concatenate a list of words in input_list, and print the output as a string.
If input_list = [‘I’,’Love’,’Python’], the output should be the string ‘I Love Python’.

from functools import reduce

q = reduce(lambda x, y: x +’ ‘+ y, input_list)

Q9. What is list comprehension and what are its advantages ?

Ans9. List comprehension is an efficient way of creating a list based on the values of existing lists in Python.

The list comprehension can be written in the following format:

newList = [ expression(element) for element in oldList if condition ] 

Advantages of List Comprehension

  1. Memory efficient than loops
  2. Space efficient than loops
  3. Transform iterative statements into a one-liner code

Q10. Write a program to extract the words that start with a vowel from a list input_list=[wood, old, apple, big, item, euphoria] using list comprehensions.

Ans10. The program of list comprehension is given below:

input_list=['wood', 'old', 'apple', 'big', 'item', 'euphoria']
list_vowel = [word for sentence in input_list for word in sentence.split() if word[0].lower() in vowel]


Q11. What is dictionary comprehension?

Ans11. Dictionary comprehension is used for transforming one dictionary into another based on certain conditions.

Q12. Write a program to generate a dictionary that contains the key-value pairs i: i**3 where ‘ i ‘ is an integer number from 1 to n (both 1 and n included). 

For example, if the input is n=5, the output should be a dictionary as follows:

{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
n = 5

dictionary = {num:num**3 for num in range(1,n+1)}

Q12. What is the difference between arrays and lists in python?


A list is a collection of heterogenous items i.e., items with different data typesThe array is a collection of homogenous items means items with the same data types
Consumes larger memoryArrays are memory efficient
Easy modification of data in the listIt does not allow easier modification of data
The complete list can be accessed without using any loopLooping is mandatory for accessing all items in arrays.

Q13. What is the difference between **args and **kwargs?

Ans13. The **args is used in the python function for passing variable length non-keyword arguments.

For example:

def myFun(*argv):
    for arg in argv:
myFun('Hello', 'Welcome', 'to', 'Python')

The **kwargs is used in the python function for passing variable-length keyword arguments.

For example:

def emp_det(**det):
    for key, value in det.items():
        print("{} is {}".format(key,value))

emp_det(Firstname="Mahesh", Lastname="Manjrekar", Age=48, Phone=987654321)

Q14. What is the difference between lists and tuples?


Lists can be modified i.e., mutableTuples cannot be modified i.e., immutable
Lists operations are time-consumingTuple operations are faster
Lists consume more memoryTuples are memory efficient
Lists are used for operations such as insertion and deletionTuples are generally used for accessing elements
Lists have many built-in methodsTuples have relatively lesser built-in methods

Q15. What are the restrictions on dictionary Keys?

Ans15. Any type of value can be assigned as a dictionary key in Python.

As we can see below example that integer, float, and Boolean objects are used as keys. Apart from that, we can also use built-in objects like types and functions as keys:

dict_ex = {42: 'aaa', 2.78: 'bbb', True: 'ccc', int:12, float:2.43}

Restrictions on Keys

  1. Duplicate keys are not allowed
  2. Secondly, a dictionary key must be of immutable type i.e., tuple, strings, etc.

Q16. What are the different types of operators in Python?

Ans16. In Python, there are basically 7 types of operators:

  1. Arithmetic operators (+,-,%,/,//,*,**)
  2. Relational operators (<, <=,>,>=,=,!=)
  3. Assignment operators (+=,-=,=,/=,%=,//=)
  4. Bit-wise operators (&,|, ^,<<,>>,~)
  5. Logical operators (and, or, not)
  6. Membership operators (in, not in)
  7. Identity operators (is, is not)

Q17. What are iterables in Python?

Ans17. An iterable is an object on which we can loop over or iterate using for loop. Examples of iterables are lists, tuples, dictionaries, sets, strings, etc.

Q18. What are the key features introduced in Python 3.9 version?

Ans18. The following new features are added in Python 3.9 version

  1. Dictionary Function: Two new operators are introduced in dictionary operations

a.) (|) union — to join or combine two dictionaries while maintaining the original dictionaries.

x = {1: 'Ajay', 2: 'Binod', 3:'China'}
y = {4: 'Dinesh', 5: 'Elena'}
z = x | y

b.) (|=) update — merge two dictionaries in place.

x = {1: 'Ajay', 2: 'Binod', 3:'China'}
y = {4: 'Dinesh', 5: 'Elena'}
x |= y

2. New methods introduced in Strings: Two methods removeprefix(prefix) and removesuffix(suffix) have been added to easily remove an unneeded prefix or a suffix from a string.

3. New Timezone module introduced: Python 3.9 has introduced a new module zoneinfo for promoting the use of IANA (Internet Assigned Numbers Authority) time zone database. IANA database is a well-maintained and extensively utilized database.

4. New Module Graphlib introduced: A new module, graphlib, is also introduced that contains the graphlib.TopologicalSorter class to offer functionality to perform topological sorting of graphs. 

Q19. What if a function doesn’t include a return statement, is it valid?

Ans19. First of all, it’s a valid function because in Python all the functions return a particular value “None” if it doesn’t include a return statement.

Q20. What are docstrings in Python?

Ans20. In Python, docstrings are string literals used for documenting functions, classes, and modules. They are placed inside triple quotation marks.

def square(n):
    '''Takes in a number n, returns the square of n. This is docstring example'''
    return n**2

Q21. Write a Python program to reverse a string

Ans21. There are multiple methods for reversing the string such as string slice operation, for loop, using recursion, etc.

  1. ) Reverse string using Slice operation


2.) Reverse string using for loop

def reverse_str(str1):
    for c in str1:
    return s1


3.) Reverse string using recursion

def reverse_recursion(s):
    if len(s) == 0:
        return s
        return reverse_recursion(s[1:]) + s[0]


Q22. Write a Python program to extract the key of a minimum value from the following dictionary

sample_dict = {
‘Physics’: 82,
‘Math’: 65,
‘History’: 75

Ans22. The program for extracting keys having minimum value is given below:

print(min(sample_dict, key=sample_dict.get))

Similarly, you can use max in place of min for extracting the maximum value from the dictionary.

Q23. Write a Python program to create a dictionary having a count of the occurrences of each character in the word.

Ans23. For solving the above problem we have to iterate over each of the characters in the word and maintain the status of each character in the form of a dictionary key and its value as a count of occurrence.

def count_occ(str1):

    for ele in str1:
        if ele in dct:
    return dct

# calling function

Q24. Write a program in Python to remove an empty character from a list sequence.

Ans.24 Let’s assume the input list is given below and we have to remove the empty character from it.

Input List : [“abc”,””,”123″]

lst =["abc","","123"]

new_lst = list(filter(None,lst))

Q25. Write a program in Python to convert strings to proper sentence cases in English.


input_str= "This is a string. this is another string."

def sentence_case(str1):
    words = str1.split(". ")
    return print(". ".join([word.capitalize() for word in words]))


Leave a Comment