71 Python Interview Questions and Answers [New] – Get Ready for Technical Round

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Welcome to the second part of DataFlair’s Python Interview Questions and Answer Series. If you are the first time visitor then you must take a quick look at the series –

As I told you, this is the second part, it mainly focuses on intermediates. In all the parts we have divided the questions into below subcategories so that it will be easier for you to find the question and answer you are searching for. Also, as per the feedback, this is the best way for Python Interview Preparations. Have a look –

  • Basic Python Interview Questions for Intermediates
  • Top Python Interview Questions
  • Python Developer Interview Questions
  • Python OOPS and Library Interview Questions
  • Technical Python Interview Questions and Answers
  • Advanced Python Interview Questions
  • Open-ended Python Interview Questions

Basic Python Interview Questions for Intermediates

Below are some basic python interview questions for intermediates, I recommend you to try to answer them by yourself. If you feel you are not able to answer the question, refer to the answers given by interview experienced.

Q.1. When is the else part of a try-except block executed?

In an if-else block, the else part is executed when the condition in the if-statement is False. But with a try-except block, the else part executes only if no exception is raised in the try part.

Q.2. If a list is nums=[0,1,2,3,4], what is nums[-1]?

This code does not throw an exception. nums[-1] is 4 because it begins traversing from right

Q.3. What is the PYTHONPATH variable?

PYTHONPATH is the variable that tells the interpreter where to locate the module files imported into a program. Hence, it must include the Python source library directory and the directories containing Python source code. You can manually set PYTHONPATH, but usually, the Python installer will preset it.

Q.4. Explain join() and split() in Python.

join() lets us join characters from a string together by a character we specify.

>>> ','.join('12345')


split() lets us split a string around the character we specify.

>>> '1,2,3,4,5'.split(',')

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

Q.5. Explain the output of the following piece of code-


This actually gives us an error- a TypeError. This is because map() has no len() attribute in their dir().

Important for InterviewPackage of top 5 Python Projects with source code

Q.6. Explain a few methods to implement Functionally Oriented Programming in Python.

Sometimes, when we want to iterate over a list, a few methods come in handy.

a. filter()

Filter lets us filter in some values based on conditional logic.

>>> list(filter(lambda x:x>5,range(8)))

[6, 7]

b. map()

Map applies a function to every element in an iterable.

>>> list(map(lambda x:x**2,range(8)))
[0, 1, 4, 9, 16, 25, 36, 49]

c. reduce()

Reduce repeatedly reduces a sequence pair-wise until we reach a single value.

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


Q.7. So what is the output of the following piece of code?


This outputs 2 because the length of this list is 2. list(map(list,x)) is [[‘a’, ‘b’], [‘c’, ‘d’]], and the length of this is 2.

Q.8. Is del the same as remove()? What are they?

del and remove() are methods on lists/ ways to eliminate elements.

>>> list=[3,4,5,6,7]
>>> del list[3]
>>> list

[3, 4, 5, 7]

>>> list.remove(5)
>>> list

[3, 4, 7]

While del lets us delete an element at a certain index, remove() lets us remove an element by its value.

Q.9. How do you open a file for writing?

Let’s create a text file on our Desktop and call it tabs.txt. To open it to be able to write to it, use the following line of code-

>>> file=open('tabs.txt','w')

This opens the file in writing mode. You should close it once you’re done.

>>> file.close()

Q.10. Explain the output of the following piece of code-

>>> tuple=(123,'John')
>>> tuple*=2
>>> tuple

(123, ‘John’, 123, ‘John’)

In this code, we multiply the tuple by 2. This duplicates its contents, hence, giving us (123, ‘John’, 123, ‘John’). We can also do this to strings:

>>> 'ba'+'na'*2


Q.11. Differentiate between the append() and extend() methods of a list.

The methods append() and extend() work on lists. While append() adds an element to the end of the list, extend adds another list to the end of a list.

Let’s take two lists.

>>> list1,list2=[1,2,3],[5,6,7,8]

This is how append() works:

>>> list1.append(4)
>>> list1

[1, 2, 3, 4]

And this is how extend() works:

>>> list1.extend(list2)
>>> list1

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

You must check the detailed description for Lists in Python

Q.12. What are the different file-processing modes with Python?

We have the following modes-

  • read-only – ‘r’
  • write-only – ‘w’
  • read-write – ‘rw’
  • append – ‘a’

We can open a text file with the option ‘t’. So to open a text file to read it, we can use the mode ‘rt’. Similarly, for binary files, we use ‘b’.

Q.13. What does the map() function do?

map() executes the function we pass to it as the first argument; it does so on all elements of the iterable in the second argument. Let’s take an example, shall we?

>>> for i in map(lambda i:i**3, (2,3,7)):


This gives us the cubes of the values 2, 3, and 7.

Q.14. Explain try, raise, and finally.

These are the keywords we use with exception-handling. We put risky code under a try block, use the raise statement to explicitly raise an error, and use the finally block to put code that we want to execute anyway.

Q.15. What happens if we do not handle an error in the except block?

If we don’t do this, the program terminates. Then, it sends an execution trace to sys.stderr.

Q.16. Is there a way to remove the last object from a list?

Yes, there is. Try running the following piece of code-

>>> list=[1,2,3,4,5
>>> list.pop(-1)


>>> list

[1, 2, 3, 4]

Q.17. How will you convert an integer to a Unicode character?

This is simple. All we need is the chr(x) built-in function. See how.

>>> chr(52)


>>> chr(49)


>>> chr(67)


Don’t forget to check DataFlair’s latest guide on Python Built-in Functions

Q.18. Explain the problem with the following piece of code-

>>> def func(n=[]):
              #playing around
>>> func([1,2,3])
>>> func()
>>> n

The request for n raises a NameError. This is since n is a variable local to func and we cannot access it elsewhere. It is also true that Python only evaluates default parameter values once; every invocation shares the default value. If one invocation modifies it, that is what another gets. This means you should only ever use primitives, strings, and tuples as default parameters, not mutable objects.

Q.19. What do you see below?

s = a + ‘[‘ + b + ‘:’ + c + ‘]’

This is string concatenation. If a, b, and c are strings themselves, then it works fine and concatenates the strings around the strings ‘[‘, ‘:’, and ‘]’ as mentioned. If even one of these isn’t a string, this raises a TypeError.

Q.20. So does recursion cause any trouble?

Sure does:

  • Needs more function calls.
  • Each function call stores a state variable to the program stack- consumes memory, can cause memory overflow.
  • Calling a function consumes time.

Q.21. What good is recursion?

With recursion, we observe the following:

  • Need to put in less efforts.
  • Smaller code than that by loops.
  • Easier-to-understand code.

Q.22. What does the following code give us?

>>> b=(1)

Not a tuple. This gives us a plain integer.

>>> type(b)

<class ‘int’>

To let it be a tuple, we can declare so explicitly with a comma after 1:

>>> b=(1,)
>>> type(b)

<class ‘tuple’>

Q.23. Why are identifier names with a leading underscore disparaged?

Since Python does not have a concept of private variables, it is a convention to use leading underscores to declare a variable private. This is why we mustn’t do that to variables we do not want to make private.

Q.24. Can you remove the whitespaces from the string “aaa bbb ccc ddd eee”?

I can think of three ways to do this.

Using join-

>>> s='aaa bbb ccc ddd eee'
>>> s1=''.join(s.split())
>>> s1


Using a list comprehension

>>> s='aaa bbb ccc ddd eee'
>>> s1=str(''.join(([i for i in s if i!=' '])))
>>> s1


Using replace()-

>>> s='aaa bbb ccc ddd eee'
>>> s1 = s.replace(' ','')
>>> s1


Q.25. How do you get the current working directory using Python?

Working on software with Python, you may need to read and write files from various directories. To find out which directory we’re presently working under, we can borrow the getcwd() method from the os module.

>>> import os
>>> os.getcwd()


Top Python Interview Questions and Answers

Q.26. How would you randomize the contents of a list in-place?

For this, we’ll import the function shuffle() from the module random.

>>> from random import shuffle
>>> shuffle(mylist)
>>> mylist

[3, 4, 8, 0, 5, 7, 6, 2, 1]

Q.27. How do you remove the leading whitespace in a string?

Leading whitespace in a string is the whitespace in a string before the first non-whitespace character. To remove it from a string, we use the method lstrip().

>>> ' Ayushi '.lstrip()

‘Ayushi ‘

As you can see, this string had both leading and trailing whitespaces. lstrip() stripped the string of the leading whitespace. If we want to strip the trailing whitespace instead, we use rstrip().

>>> ' Ayushi '.rstrip()

‘ Ayushi’

Q.28. Below, we give you code to remove numbers smaller than 5 from the list nums. However, it does not work as expected. Can you point out the bug for us?

>>> nums=[1,2,5,10,3,100,9,24]
>>> for i in nums:
             if i<5:
>>> nums

[2, 5, 10, 100, 9, 24]

This code checks for each element in nums- is it smaller than 5? If it is, it removes that element. In the first iteration, 1 indeed is smaller than 5. So it removes that from this list. But this disturbs the indices. Hence, it checks the element 5, but not the element 2. For this situation, we have three workarounds:

Create an empty array and append to that-

>>> nums=[1,2,5,10,3,100,9,24]
>>> newnums=[]
>>> for i in nums:
       if i>=5:
>>> newnums

[5, 10, 100, 9, 24]

Using a list comprehension-

>>> nums=[1,2,5,10,3,100,9,24]
>>> newnums=[i for i in nums if i>=5]
>>> newnums

[5, 10, 100, 9, 24]

Using the filter() function-

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

[5, 10, 100, 9, 24]

Q.29. What is the enumerate() function in Python?

enumerate() iterates through a sequence and extracts the index position and its corresponding value too.

Let’s take an example.

>>> for i,v in enumerate(['Python','C++','Scala']):

0 Python
1 C++
2 Scala

Q.30. How will you create the following pattern using Python?

We will use two for-loops for this.

>>> for i in range(1,6):
       for j in range(1,i+1):

Q.31. Where will you use while rather than for?

Although we can do with for all that we can do with while, there are some places where a while loop will make things easier-

python advanced interview questions

  • For simple repetitive looping
  • When we don’t need to iterate through a list of items- like database records and characters in a string.

Want to revise the concepts of loops? Here it is – Python Loops

Q.32. Take a look at this piece of code:

>>> A0= dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
>>> A1= range(10)
>>> A2= sorted([i for i in A1 if i in A0])
>>> A3= sorted([A0[s] for s in A0])
>>> A4= [i for i in A1 if i in A3]
>>> A5= {i:i*i for i in A1}
>>> A6= [[i,i*i] for i in A1]
>>> A0,A1,A2,A3,A4,A5,A6

What are the values of variables A0 to A6? Explain.

Here you go:

A0= {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5}
A1= range(0, 10)
A2= []
A3= [1, 2, 3, 4, 5]
A4= [1, 2, 3, 4, 5]
A5= {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6= [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Now to find out what happened. A0 zips ‘a’ with 1, ‘b’ with 2, and so on. This results in tuples, which the call to dict() then turns into a dictionary by using these as keys and values.

  • A1 gives us a range object with start=0 and stop=10.
  • A2 checks each item in A1- does it exist in A0 as well? If it does, it adds it to a list. Finally, it sorts this list. Since no items exist in both A0 and A1, this gives us an empty list.
  • A3 takes each key in A0 and returns its value. This gives us the list [1,2,3,4,5].
  • A4 checks each item in A1- does it exist in A3 too? If it does, it adds it to a list and returns this list.
  • A5 takes each item in A1, squares it, and returns a dictionary with the items in A1 as keys and their squares as the corresponding values.
  • A6 takes each item in A1, then returns sublists containing those items and their squares- one at a time.

Q.33. Does Python have a switch-case statement?

In languages like C++, we have something like this:

   case ‘Ayushi’:
   case ‘Megha’:
       cout<<”Hi, user”;

But in Python, we do not have a switch-case statement. Here, you may write a switch function to use. Else, you may use a set of if-elif-else statements. To implement a function for this, we may use a dictionary.

>>> def switch(choice):
      print(switcher.get(choice,'Hi, user'))


>>> switch('Megha')


>>> switch('Ayushi')


>>> switch('Ruchi')

Hi, user

Here, the get() method returns the value of the key. When no key matches, the default value (the second argument) is returned.

Q.34. Differentiate between deep and shallow copy.

python basic interview questions

A deep copy copies an object into another. This means that if you make a change to a copy of an object, it won’t affect the original object. In Python, we use the function deepcopy() for this, and we import the module copy. We use it like:

>>> import copy
>>> b=copy.deepcopy(a)

A shallow copy, however, copies one object’s reference to another. So, if we make a change in the copy, it will affect the original object. For this, we have the function copy(). We use it like:

>>> b=copy.copy(a)

Python Developer Interview Questions

Q.35. Can you make a local variable’s name begin with an underscore? (developer)

You can, but you should not. This is because:

Local variables indicate private variables of a class, and so, they confuse the interpreter.

Q.36. Is a NumPy array better than a list?

NumPy arrays have 3 benefits over lists:

  • They are faster
  • They require less memory
  • They are more convenient to work with

Q.37. If you installed a module with pip but it doesn’t import in your IDLE, what could it possibly be?

  • Well, for one, it could be that I installed two versions of Python on my system- possibly, both 32-bit and 64-bit.
  • The Path variable in my system’s environment variables is probably set to both, but one of them prior to the other- say, the 32-bit.
  • This made the command prompt use the 32-bit version of pip to install the module I chose.
  • When I ran the IDLE, I ran the 64-bit version.

As this sequence of events unlapped, I couldn’t import the module I just installed.

Q.38. Based on your previous answer, how will you solve this issue?

I could do two things.

  • The temporary solution- I will add the path to sys manually every time I work on a new session of the interpreter.
>>> sys.path.append('C:\\Users\\Ayushi\\AppData\\Local\\Programs\\Python\\Python37\\Scripts')
  • The permanent solution- I will update the value of Path in my environment variables to hold the location of the Scripts folder for the 64-bit version first.

Q.39. If while installing a package with pip, you get the error No matching installation found, what can you do?

In such a situation, one thing I can do is to download the binaries for that package from the following location:


Then, I can install the wheel using pip.

Learn everything about Python Package

Q.40. How can you keep track of different versions of code?

To make this happen, we implement version control. For this, one tool you can use is Git.

Q.41. How do you debug a program in Python? Answer in brief.

To debug a Python program, we use the pdb module. This is the Python debugger. If we start a program using pdb, it will let us step through the code.

Python OOPS and Library Interview Questions

Q.42. Can I dynamically load a module in Python?

Dynamic loading is where we do not load a module till we need it. This is slow, but lets us utilize the memory more efficiently. In Python, you can use the importlib module for this:

import importlib
module = importlib.import_module('my_package.my_module')

Q.43. Which methods/functions do we use to determine the type of instance and inheritance?

Here, we talk about three methods/functions- type(), isinstance(), and issubclass().

a. type()

This tells us the type of object we’re working with.

>>> type(3)

<class ‘int’>

>>> type(False)

<class ‘bool’>

>>> type(lambda :print("Hi"))

<class ‘function’>

>>> type(type)

<class ‘type’>

b. isinstance()

This takes in two arguments- a value and a type. If the value is of the kind of the specified type, it returns True. Else, it returns False.

>>> isinstance(3,int)


>>> isinstance((1),tuple)


>>> isinstance((1,),tuple)


c. issubclass()

This takes two classes as arguments. If the first one inherits from the second, it returns True. Else, it returns False.

>>> class A: pass
>>> class B(A): pass
>>> issubclass(B,A)


>>> issubclass(A,B)


Q.44. Are methods and constructors the same thing?

No, there are subtle but considerable differences-

  • We must name a constructor in the name of the class; a method name can be anything.
  • Whenever we create an object, it executes a constructor; whenever we call a method, it executes a method.
  • For one object, a constructor executes only once; a method can execute any number of times for one object.
  • We use constructors to define and initialize non-static variables; we use methods to represent business logic to perform operations.

Q.45. What is a Python module?

A module is a script in Python that defines import statements, functions, classes, and variables. It also holds runnable Python code. ZIP files and DLL files can be modules too. The module holds its name as a string that is in a global variable.

Q.46. What are the file-related modules we have in Python?

We have the following libraries and modules that let us manipulate text and binary files on our file systems-


Q.47. Explain, in brief, the uses of the modules sqlite3, ctypes, pickle, traceback, and itertools.

  • sqlite3- Helps with handling databases of type SQLite
  • ctypes- Lets create and manipulate C data types in Python
  • pickle- Lets put any data structure to external files
  • traceback- Allows extraction, formatting, and printing of stack traces
  • itertools– Supports working with permutations, combinations, and other useful iterables.

Q.48. Explain inheritance in Python.

When one class inherits from another, it is said to be the child/derived/sub class inheriting from the parent/base/super class. It inherits/gains all members (attributes and methods).

Python Interview Questions - inheritance

Inheritance lets us reuse our code, and also makes it easier to create and maintain applications. Python supports the following kinds of inheritance:

  • Single Inheritance- A class inherits from a single base class.
  • Multiple Inheritance- A class inherits from multiple base classes.
  • Multilevel Inheritance- A class inherits from a base class, which, in turn, inherits from another base class.
  • Hierarchical Inheritance- Multiple classes inherit from a single base class.
  • Hybrid Inheritance- Hybrid inheritance is a combination of two or more types of inheritance.

Technical Python Interview Questions and Answers

Here comes the most important category that is technical Python Interview Questions and Answers –

Q.49. Explain memory management in Python.

Objects and data structures in Python lie on a private heap. The Python memory manager internally manages this. It delegates some work to object-specific allocators while ensuring they operate only within the private heap. Actually, the interpreter manages this heap; the user has no control over it- not even if they manipulate object pointers to memory blocks inside the heap. The Python memory manager allocates heap space to objects and other internal buffers on demand.

Q.50. Write Python logic to count the number of capital letters in a file.

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> with open('Today.txt') as today:
    for i in today.read():
        if i.isupper():


Q.51. How would you make a Python script executable on Unix?

For this to happen, two conditions must be met:

  • The script file’s mode must be executable
  • The first line must begin with a hash(#). An example of this will be: #!/usr/local/bin/python

Q.52. What functions or methods will you use to delete a file in Python?

For this, we may use remove() or unlink().

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> os.remove('try.py')

When we go and check our Desktop, the file is gone. Let’s go make it again so we can delete it again using unlink().

>>> os.unlink('try.py')

Both functions are the same, but unlink is the traditional Unix name for it.

Q.53. Can you write a function to generate the following pyramid?






def pyramid(n):
  for row in range(n):
    for space in range(n-row):
      print(' ',end='')
    for star in range(row):
    for star in range(row+1):


Q.54. How will you print the contents of a file?

>>> try:
      with open('tabs.txt','r') as f:
except IOError:
      print("File not found")

Advanced Python Interview Questions

Q.55. Explain lambda expressions. When would you use one?

When we want a function with a single expression, we can define it anonymously. A lambda expression may take input and returns a value. To define the above function as a lambda expression, we type the following code in the interpreter:

>>> (lambda a,b:a if a>b else b)(3,3.5)


Here, a and b are the inputs. a if a>b else b is the expression to return. The arguments are 3 and 3.5.

It is possible to not have any inputs here.

>>> (lambda :print("Hi"))()


Q.56. What is a generator?

Python generator produces a sequence of values to iterate on. This way, it is kind of an iterable.
We define a function that ‘yields’ values one by one, and then use a for loop to iterate on it.

>>> def squares(n):
yield i**2
>>> for i in squares(7):


Q.57. So, what is an iterator, then?

An iterator returns one object at a time to iterate on. To create an iterator, we use the iter() function.


Then, we call the next() function on it every time we want an object.

>>> next(odds)


>>> next(odds)


>>> next(odds)


>>> next(odds)


>>> next(odds)


And now, when we call it again, it raises a StopIteration exception. This is because it has reached the end of the values to iterate on.

>>> next(odds)

Traceback (most recent call last):
File “<pyshell#295>”, line 1, in <module>

Q.58. Okay, we asked you about generators and iterators, and you gave us the right answers. But don’t they sound similar?

python scripting interview questions

They do, but there are subtle differences:

  • For a generator, we create a function. For an iterator, we use in-built functions iter() and next().
  • For a generator, we use the keyword ‘yield’ to yield/return an object at a time.
  • A generator may have as many ‘yield’ statements as you want.
  • A generator will save the states of the local variables every time ‘yield’ will pause the loop. An iterator does not use local variables; it only needs an iterable to iterate on.
  • Using a class, you can implement your own iterator, but not a generator.
  • Generators are fast, compact, and simpler.
  • Iterators are more memory-efficient.

Q.59. What is a decorator?

A decorator is a function that adds functionality to another function without modifying it. It wraps another function to add functionality to it. Take an example.

>>> def decor(func):
   def wrap():

return wrap

>>> @decor
def sayhi():
>>> sayhi()


Decorators are an example of metaprogramming, where one part of the code tries to change another.

Q.60. What is Monkey Patching?

Monkey patching refers to modifying a class or module at runtime (dynamic modification). It extends Python code at runtime.

For example:

from pkg.module import MyClass
def sayhello(self):


Wait!! You should check the career opportunities in Python.  

Hope you have enjoyed the above Python Interview Questions, but this is not the end. You need to practice some open-ended or behavior-based interview questions to crack your next Python Interview.

Open-ended Interview Questions

Q.61. Why should we hire you?

Q.62. What personal growth did you see in yourself after your last job?

Q.63. Tell me about a situation you found yourself stuck in your previous job. How did you work your way out?

Q.64. How would you resolve a dispute with a colleague? Did you face such a situation in your previous job?

Q.65. What do you expect us to do better than your previous employer?

Q.66. Have you ever changed someone’s opinion at work?

Q.67. What are your thoughts on office gossips?

Q.68. What would be the weakest link to your performance?

Q.69. Where do you think the industry is going in the next 15 years?

Q.70. What legacy did you leave in your previous job? Did you develop an innovative solution?

Q.71. Would you prefer working alone, or in a small/large team?

Try to answer the above questions by yourself. If you need any help, comment below.

Have you developed any Project in Python yet? If not, then first you need to practice top Python Projects with their source code. Once you are done with this, refer to the last part of Python Interview Question and Answer Series (link at the top)

If this helped you, thank me through the comments.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google


15 Responses

  1. Manjula arjun says:

    Thank you very much…very useful info

    • DataFlair Team says:

      Thanks for the feedback. If you liked our Python interview questions article, share it on social media with your friends and colleagues.

  2. Shwetha says:

    Very very informative .. thank you so much

  3. Mohit says:

    Thank you soo much..

  4. Akshatha says:

    Thank you very much, it was much needed

  5. M.HEENA says:

    its useful for us…..

  6. CP says:

    Hi DataFlair Team,

    I read this article and this is very good but some syntax error in your example (code).
    please improve this.

    thank you

  7. Ashraful says:

    lots of thanks for hard work

    • DataFlair Team says:

      Thanks for the feedback. If you liked our Python interview questions article, share it on social media with your friends and colleagues.

  8. Supriya says:

    This is very useful to me and very interesting, thank u soo much

  9. Manishma says:

    Q.5. Explain the output of the following piece of code-

    the output is 2, not a TypeError. You misslead the readers while your article is on the top of google ‘python interview quiestion’ please check

  10. sunnywalden says:

    Please note that Python has switch-case statement since 3.10, thw answer of Q.33 may not corret any more.

Leave a Reply

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