[ 35+ ] Python Interview Questions & Answers [BEST & NEW]-2020

[ 35+ ] Python Interview Questions & Answers [BEST & NEW]

Last updated on 05th Jun 2020, Blog, Interview Questions

About author

Shalini (Sr Technical Project Manager )

Delegates in Corresponding Technical Domain with 6+ Years of Experience. Also, She is a Technology Writer for Past 3 Years & Share's this Informative Blogs for us.

(5.0) | 15212 Ratings 4455

Python is a general purpose and high level programming language. You can use Python for developing desktop GUI applications, websites and web applications. Also, Python, as a high level programming language, allows you to focus on core functionality of the application by taking care of common programming tasks.

1. What does the <yield> keyword do in python?


The yield keyword can turn any function into a generator. It works like a standard return keyword. But it will always return a generator object. A function can have multiple calls the <yield> keyword.


  • def testgen(index):
  • weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’] yield weekdays[index] yield weekdays[index+1] day = testgen(0)
  • print next(day), next(day)
  • Output:
  • Sun mon

2. What are the different ways to create an empty NumPy array in python?


There are two methods we can apply to create empty NumPy arrays.

The first method:

  • import numpy
  • numpy.array([])

The second method:

  • # Make an empty NumPy array
  • numpy.empty(shape=(0,0))

3. Can’t concat bytes to str?


This is providing to be a rough transition to python on here: 

  • f = open( ‘myfile’, ‘a+’ )
  • f.write(‘test string’ + ‘\n’)
  • key = “pass:hello”
  • plaintext=subprocess.check_output([‘openssl’,’aes-128-cbc’,’-d’, ‘-in’,test,’-base64′,’-pass’, key])
  • print (plaintext)
  • f.write (plaintext + ‘\n’)
  • f.close()
  • The output file looks like:
  • test string

4. Explain different ways to trigger/ raise exceptions in your python script?


Raise used to manually raise an exception general-form:

  • raise exception-name (“message to be conveyed”)
  • voting_age = 15
  • if voting_age < 19: raise ValueError(“voting age should be at least 19 and above”)


ValueError: voting age should be at least 19 and above 2.assert statements are used to tell your program to test that condition attached to assert keyword, and trigger an exception whenever the condition becomes false. Eg: a = -10

  • assert a > 0 #to raise an exception whenever a is a negative number



Another way of raising an exception can be done by making a programming mistake, but that is not usually a good way of triggering an exception

5. Why is not__getattr__invoked when attr==’__str__’?


The base class object already implements a default __str__ method, and __getattr__function is  called for missing attributes. The example is that we must use the __getattribute__ method instead, but beware of the dangers.

class GetAttr(object):

  • def __getattribute__(self, attr):
  • print(‘getattr: ‘ + attr)
  • if attr == ‘__str__’:
  • return lambda: ‘[Getattr str]’
  • else:
  • return lambda *args: None
  • A better and more readable solution to simply override the __str__ method explicitly.

class GetAttr(object):

  • def __getattr__(self, attr):
  • print(‘getattr: ‘ + attr)
  • return lambda *args: None
  • def __str__(self):
  • return ‘[Getattr str]’

6. What do you mean by list comprehension?


The process of creating a list performing some operation on the data so that can be accessed using an iterator is referred to as list comprehension.


  • [ord (j) for j in string.ascii_uppercase]



7. What will be the output of the code:def foo (i=[])?


  • i.append (1)
  • return i
  • >>> foo ()
  • >>> foo ()


[1] [1,1] The argument to the function foo is evaluated once when the function is defined

However since it is a list on every all the list is modified by appending a 1 to it.

8. How to Tic tac toe computer move?


Below The code of computer move in the game tic tac toe in python

def computermove(board,computer,human):

  • def computermove(board,computer,human):
  • movecom=”
  • rmoves=rd(0,8)
  • for movecom in legalmoves(board):
  • board[movecom]=computer
  • if winner(board)==computer:
  • return movecom
  • board[movecom]=”
  • for movecom in legalmoves(board):
  • board[movecom]=human
  • if winner(board)==human:
  • return movecom
  • board[movecom]=”
  • while rmoves not in legalmoves(board):
  • rtmoves=rd(0,8)
  • return rmoves

9. Explain about ODBC and python?


ODBC (Open Database Connectivity) API standard allows the connections with any that supports the interface such as the PostgreSQL database or Microsoft access database in a transparent manner

Three types of ODBC modules for python:

  • PythonWin ODBC module: limited development
  • mxODBC: a commercial product
  • pyodbc: This is open source python package

10. How to implement the decorator function, using dollar ()?


  • def dollar(fn):
  • def new(*args):
  • return ‘$’ + str(fn(*args))
  • return new
  • @dollar
  • def price(amount, tax_rate):
  • return amount + amount*tax_rate
  • print price(100,0.1)



11. How to count the number of instances?

You have a class A, you want to count the number of A instance.

Hint: use staticmethod


  • class A:
  • total = 0
  • def __init__(self, name):
  • self.name = name
  • A.total += 1
  • def status():
  • print “Number of instance (A) : “, A.total
  • status = staticmethod(status)
  • a1 = A(“A1”)
  • a2 = A(“A2”)
  • a3 = A(“A3”)
  • a4 = A(“A4”)
  • A.status()


The number of instance (A) : 4

12. What are the Arithmetic Operators that Python supports?


 ‘+’     : Addition

‘-’     : Subtraction

‘*’    : Multiplication

‘/’: Division

‘%’: Modulo division

‘**’: Power Of

‘//’: floor div

Python does not support unary operators like ++ or – operators. Python supports “Augmented Assignment Operators”. i.e.,

A += 10 Means A = A+10

B -= 10 Means B = B-10

13. How do you reload a Python module?


All that needs to be a module object to the imp.reload() function or just reload() in Python 2.x, and the module will be reloaded from its source file. Any other code references symbols exported by the reloaded module, they still are bound to the original code.

14. How does Python handle Compile-time and Run-time code checking?


Python supports compile-time code checking up to some extent. Most checks for variable data types will be postponed until run-time code checking. When an undefined custom function is used, it will move forward with compile-time checking. During runtime, Python raises exceptions against errors.

15. What are Supporting Python packages for data science operations?


  • Pandas: A package providing flexible data structures to work with relational or labeled data.
  • NumPy: A package that allows working with numerical based data structures like arrays and tensors.
  • Matplotlib: A 2D rendering engine written for Python.
  • Tensorflow: A package used for constructing computational graphs.

16. What are the ones that can be used with pandas?


A python dict, ndarray or scalar values can be used with Pandas. The passed index is a list of axis labels.

17. How To Add an Index, Row or Column to a Pandas DataFrame?


The index can be added by calling set_index() on programmer DataFrame.

For accessing rows, loc works on labels of programme index, iloc works on the positions in programme index, it is a more complex case: when the index is integer-based, the programmer passes a label to ix[index].

18. How To Create an Empty DataFrame?


The function that programmers will use is the Pandas Dataframe() function: it requires the programmer to pass the data that the programmer wants to put in, the indices and the columns.

19. Does Pandas Recognize Dates When Importing Data?


Yes. but programmers need to help it a tiny bit: add the argument parse_dates when programmer by reading in data from, let’s say, a comma-separated value (CSV) file.

20. How to convert a NumPy array to a Python List?


  • Use tolist():
  • import numpy as np
  • >>> np.array([[1,2,3],[4,5,6]]).tolist()

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

21. How to set the figure title and axes labels font size in Matplotlib?


Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

    Subscribe For Free Demo

    22. x = [‘android’, ‘basket’, ‘cat’, ‘doctor’, ‘element’, ‘forest’, ‘gun’]


    • What is x[-1]
    • ‘gun’
    • What is x[3:-3]
    • [‘doctor’]

    23. x = (‘animal’, 1, ‘boost’, 4)


    • What is type(x)?
    • tuple
    • How can you add elements to x?
    • A tuple is an immutable object so adding is not possible

    24. x = [1,2,1,3,4,8,2,4,5]


    • How can you sort the elements in x?
    • X.sort()
    • How can you print only unique elements in x?
    • List(set(x))

    25. What does an object() do?


    It returns a featureless object that is a base for all classes. Also, it does not take any parameters.

    26. X = [1,2,3,4,5]

    print elements

    Which of the following is correct:

    1. x is a string
    2. x is an integer
    3. x is a list
    4. x is a tuple


    Option: 3 = x is a list

    27. To open a file “c:\scores.txt” for writing, we are using

    a) outfile = open(“c:\scores.txt”, “r”)

    b) outfile = open(file = “c:\scores.txt”, “r”)

    c) outfile = open(“c:\\scores.txt”, “w”)

    d) outfile = open(file = “c:\\scores.txt”, “o”)


    Option: c = outfile = open(“c:\\scores.txt”, “w”)

    28. When will the else part of “try-except-else” be executed?

    a) always

    b) when no exception occurs

    c) when an exception occurs

    d) when an exception occurs to except block


    Option: b = when no exception occurs

    29. What is the output of 33 == 33.0 ?

    A – False

    B – True

    C – 33

    D – None of the above


    Option: B = True

    30. What is the output of following the code ?

    x = 2

    y = 10

    x * = y * x + 1

    A – 42

    B – 41

    C – 40

    D – 39


    Option: A = 42

    31. How can we generate random numbers in python using methods?

    A – random.uniform ()

    B – random.randint()

    C – random.random()

    D – All of the above


    Option: C = random.random()

    32. What is output for − max(”please help ”) ?

    A – s

    B – a blank space character

    C – e

    D – p


    Option: A = s

    33. What is the output of the following code?

    eval(”1 + 3 * 2”)

    A – ‘1+6’

    B – ‘4*2’

    C – ‘1+3*2’

    D – 7


    Option: D = 7

    34. What is the out of the code?

    def rev_func(x,length):

    print(x[length-1],end=” ”)


    x=[11, 12, 13, 14, 15] rev_func(x,5)

    A – The program runs fine without error.

    B – Program displays 15 14 13 12 11.

    C – Program displays 11 12 13 14 15.

    D – Program displays 15 14 13 12 11 and then raises an index out of range exception.


    Option : D = Program displays 15 14 13 12 11 and then raises an index out of range exception.

    35. Select the correct code to create a check button under parent frame1 and it should be bound to v1?

    A – CheckButton(frame1, text=”Bold” , command=CheckButton)

    B – Checkbutton(frame1 , text=”Bold’’ ,variable=v1 ,command=processCheckbutton)

    C – Checkbutton(frame1,text=”Bold”,variable=v1.set(),command=v1.set(process ton)

    D–Checkbutton(frame.set(f1),text.set(”bold”) ,command=v1.set(processCheckbutton)


    Option : B = Checkbutton(frame1 , text=”Bold’’ ,variable=v1, command=processCheckbutton)

    Course Curriculum

    Get On-Demand Python Training with Advanced Concepts By IT Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    36. You are using a grid manager then which option is best suitable to place a component in multiple rows and columns?

    A –  Only row

    B – Columnspan and rowspan

    C – Only column

    D – Only rowspan


    Option: B = Columnspan and rowspan

    37. Which can be an Identifier among them in Python?

    A – 1abc

    B – $12a

    C – _xy1

    D – @python


    Option: C = _xy1

    38. What will be the output of the following code?

    • def total(initial = 5, *num, **key):
    • count = initial
    • for n in num:
    • count+=n
    • for k in key:
    • count+=key[k] return count
    • print(total(100,2,3, clouds=50, stars=100))

    A – 260

    B – 160

    C – 155

    D – 255


    Option: D = 255

    39. What is a dictionary in Python?


    The built-in datatypes in Python are called a dictionary. It defines a one-to-one Relationship between keys and values. It contains a pair of keys and their corresponding values. Dictionaries are indexed by keys. It is a collection which is unordered, changeable and indexed.

    Let’s take an example:   The following example contains some keys. State, Capital,Language. Their corresponding values are Karnataka, Bangalore, and Kannada respectively.

    • Dict={ ‘Country’:’Karnataka’,’Capital’:’Bangalore’,’Language’:’Kannada’}
    • print dict[Country] Karnataka
    • Print dict[Capital] Bangalore
    • Print dict[Language] Kannada

    40. How memory is managed in Python?


    Python private heap space manages python memory. Python heap has all Python objects and data structures. Access to this private heap is restricted to programmers; also Python private heap is taken care of by the interpreter.

    The core API gives access to some tools for the programmer to code. Python memory manager allocates python heap space.

    41. What is the output of this following statement?

    • f=none
    • for i in range(5);
    • with open(“data.txt”, ”w”) as f:
    • if I>1:
    • break
    • print f.closed

    • A) True
    • B) False
    • C) None
    • D) Error


    Option: A = True

    42. Write a coding in Find the Largest Among three numbers?

    • num1 = 10
    • num2 = 14
    • num3 = 12
    • if (num1 >= num2) and (num1 >= num3):
    • largest = num1
    • elif (num2 >= num1) and (num2 >= num3):
    • largest = num2
    • else:
    • largest = num3
    • print(“The largest number between”,num1,”,”,num2,”and”,num3,”is”,largest)


     The largest Number is 14.0

    43. What is Lambda in Python?


    lambda is an one line anonymous function,


    • Sum=lambda i,c:i+c

    44. What is the difference between list and tuples?


    • Lists are the mutable elements where we are able to perform the task in the existing variable. Lists can able to reduce the utilization of memory
    • Tuples are immutable so it can execute faster when compared with list. But it will wastes the memory.

    45. What are the key features of Python?


    • It doesn’t have any structure or syntax except the indentation.
    • It can execute the instructions fastly because of the RISC architecture.
    • It consumes only less memory because of no internal executions.
    • It doesn’t have any compilers compilation that can be done at the time of the program.

    46. How to delete a file in Python?


    In Python, Delete a file using this command,

    • os.unlink(filename)


    • os.remove (filename)

    47. What is the usage of help() and dir() function in Python?


    Help() and dir() both functions are accessible from the Python interpreter used for viewing a consolidated dump of built-in functions. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.

    48. Which of the following statements create a dictionary? (Multiple Correct Answers Possible)

    a) d = {}

    b) d = {“john”:40, “peter”:45}

    c) d = {40:”john”, 45:”peter”}

    d) d = (40:”john”, 45:”50”)

    e) All


    Option: e = All

    49. Which of the following is an invalid statement?

    a) abc = 1,000,000

    b) a b c = 1000 2000 3000

    c) a,b,c = 1000, 2000, 3000

    d) a_b_c = 1,000,000


    Option: c = a,b,c = 1000, 2000, 3000

    50. What is the output of the following?

    • try:
    • if ‘1’ != 1:
    • raise “someError”
    • else:
    • print(“someError has not occured”)
    • except “someError”:
    • print (“someError has occurred”)
    • a) someError has occurred
    • b) someError has not occured
    • c) invalid code
    • d) none of the above


    Option : b = someError has not occured

    Course Curriculum

    Learn Python Certification Course & Become a Certified Python Expert

    Weekday / Weekend BatchesSee Batch Details

    51. What is the maximum possible length of an identifier?

    a) 31 characters

    b) 63 characters

    c) 79 characters

    d) None of the above


    Option : d = None of the above

    52. Differentiate list and tuple with an example?


    Difference is that a list is mutable, but a tuple is immutable.


    • >>> mylist=[1,3,3]
    • >>> mylist[1]=2
    • >>> mytuple=(1,3,3)
    • >>> mytuple[1]=2

    TypeError: ‘tuple’ object does not support item assignment

    53. Which operator will be helpful for decision making statements?


    comparison operator

    54. Out of two options, which template by default flask is following?

    a) Werkzeug

    b) Jinja2


    Option: b = Jinja2

    55. Point out the use of help() function


    Help on function copy in module copy:

    • copy(x)

    Shallow copy operation on arbitrary Python objects.

    56. From below select which data structure is having a key-value pair ?





    Option: c = Dictionary

    57. Differentiate *args and **kwargs?


    *args : We can pass multiple arguments we want like list or tuples of data

    **kwargs : we can pass multiple arguments using keywords

    58. Use of Negative indices?


    It helps to  slice from the back

    mylist=[0,1,2,3,4,5,6,7,8] >>>mylist[-3] 6

    59. Give an example for join() and split() functions


    >>> ‘,’.join(‘12345’)


    >>> ‘1,2,3,4,5’.split(‘,’)

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

    60. Python is case sensitive ?




    Option: a = True

    61. List out loop breaking functions


    • break
    • continue
    • pass

    62. What is the syntax for exponentiation and give examples?



    eg: 2**3 = 8

    63. Which operator helps to do additional operations ?


    arithmetic operator

    64. How to get all keys from a dictionary ?



    65. Give one example for multiple statements in a single statement?



    66. What is the output for the following code?

    • >> define expand list(val, list=[]):
    • list.append(val)
    • return list
    • >>> list1 = expandlist (10)
    • >>> list2 = expand list (123,[])
    • >>> list3 = expand list (‘a’)
    • >>> list1,list2,list3


    ([10, ‘a’], [123], [10, ‘a’])

    67. Number of argument’s that range() function can take ?

    a. 3

    b. 5



    Option : a =3

    68. Give an example to capitalize the first letter of a string?


    • a=’test’
    • print a[0].upper()
    • Test

    69. How to find whether a string is alphanumeric or not?


    • str = “hjsh#”;
    • print str.isalnum()


    70. Which method will be used to delete a file ?


    • os.remove(filename)

    71. What is the difference between match & search in the regex module in python?


    Match Checks for a match only at the beginning of the string, while search checks for a match anywhere in the string.

    72. Can we change tuple values? If yes, give an example.


    Since tuples are immutable, so we cannot change tuple value in its original form but we can convert it into a list for changing its values and then convert again to tuple.

    Below is the example:

    • my_tuple=(1,2,3,4)
    • my_list=list(my_tuple)
    • my_list[2]=9
    • my_tuple=tuple(my_list)

    73. What is the purpose of __init__ in Class ? Is it necessary to use __init__  while creating a class ?


     __init__ is a class constructor in python.  __init__  is called when we create an object for a class and it is used to initialize the attribute of that class.

    Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    eg : 

    • def __init__ (self, name ,branch , year)
    • self.name= name
    • self.branch = branch
    • self.year =year
    • print(“a new student”)

    No, It is not necessary to include __init__ as your first function every time in class.

    74. Can Dictionary have duplicate keys  ?


    Python Doesn’t allow duplicate keys  however if a key is duplicated the second key-value pair will overwrite the first as a dictionary can only have one value per key.

    For eg :

    • >>> my_dict={‘a’:1 ,’b’ :2 ,’b’:3}
    • >>> print(my_dict)
    • {‘a’: 1, ‘b’: 3}

    75. What happens if we call a key that is not present in a dictionary and how to tackle that kind of error ?


    It will return a Key Error . We can use the get method to avoid such conditions. This method returns the value for the given key, if it is present in the dictionary and if it is not present  it will return None (if get() is used with only one argument).

    Dict.get(key, default=None)

    76. What is the difference b/w range and arange function in python?


    numpy.arange :  Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) .the interval including start but excluding stop. It returns an Array .

    • numpy.arange([start, ]stop, [step, ]dtype=None)

    Range : The range function returns a list of numbers between the two arguments (or one) you pass it.

    77. What is the difference b/w panda series and a dictionary in python?


    Dictionaries are python’s default data structures which allow you to store key: value pairs and it offers some built-in methods to manipulate your data.

    78. Why does it need to create a virtual environment before starting a project in Django ?


    A Virtual Environment is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects.

    Benefit of creating virtualenv : We can create multiple virtualenv , so that every project has a different set of packages .

    For eg: If one project we run on two different versions of Django , virtualenv can keep those projects fully separate to satisfy both requirements at once.It makes it easy for us to release our project with its own dependent modules.

    79. How to write a text from another text file in python ?


    Below is the code for the same.

    • import os
    • os.getcwd()
    • os.chdir(‘/Users/username/Documents’)
    • file = open(‘input.txt’ ,’w’)
    • with open(“output.txt”, “w”) as fw, open(“input.txt”,”r”) as fr:

    80. What is the difference between input and raw_input?


    There is no raw_input() in python 3.x  only input() exists. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). In python 3.x  We  can  manually compile and then eval for getting old functionality.

    81. What are all the important modules in python  required for Data Science ?


    Below are important module for a Data Science :

    • NumPy
    • SciPy
    • Pandas
    • Matplotlib
    • Seaborn
    • Bokeh
    • Plotly
    • SciKit-Learn
    • Theano
    • TensorFlow

    82. What is the use of list comprehension ?


    List comprehension is used to transform one list into another list. During this process, list items are  conditionally included in the new list and each item is transformed as required. Eg.

    • my_list=[] my_list1=[2,3,4,5] Using  “for “ loop :
    • for i in my_list1:
    • my_list.append(i*2)
    • Using List comprehension :
    • my_list2=[i*2 for i in my_list1] print(my_list2)

    83. What is the lambda function ?


    lambda function is used for creating small, one-time and anonymous function objects in Python.

    84. What is the use of sets in python?


    A set is a  type of python data Structure which is unordered and unindexed. It  is declared in curly braces . sets are used when you required only unique elements .my_set={ a ,b ,c,d}

    85. Does python have a private keyword in python ? how to make any variable private in python ?


    It does not have a private keyword in python and for any instance variable to make it private you can __  prefix in the  variable so that it will not be visible to the code outside of the class .

    Eg . 

    • Class A:
    • def __init__(self):
    • self.__num=345
    • def printNum(self):
    • print self.__num

    86. What is pip and when it is used ?


    It is a  package management system and it is used to install many python packages. Eg. Django , mysql.connector

    • Syntax : pip install packagename
    • pip install Django : to install Django module

    87. What is the head and tail method for Data frames in pandas ?


    • Head : it will give the first N rows of Data frame.
    • Tail : it will give the last N rows of the Data frame. By default it is 5.

    88. How to change a string in a list ?


    we can use the split method to change an existing string into a list: 

    • s= ‘Hello sam good morning ’
    • s.split()
    • print(s)
    • [‘hello’ , ‘sam’ , ‘good’ , ‘morning’]

    89. How to take hello as output from below nested list using indexing concepting in python.

    my_list=[1,2,3,[5,6,7, [2,7,[‘hello’], 4,5]],3,4]


    • my_list[3][3][2][0] print(my_list)

    90. What is a list when we have to use it ?


    Lists always store homogeneous elements.  we have to use the lists when the data is the same type and when accessing is more insteading of inserting  in memory.

    91. What is dict when we have to use it ?


    Dict is used to store key value pairs and key is calculated using hash key. This is used when we want to access data in O(1) time as big O notation in the average case. Dict I used in u can say supermarket to know the price of corresponding while doing billing

    92. What is tuple when we have to use it ?


    Tuple is heterogeneous and we have to use it when data is different types.

    93. Is String Immutable ?


    Yes because it creates an object in memory so if you want to change through indexing it will throw an exception since it can’t be changed.

    94. How to handle Exception ?


    We can handle exceptions by using try catch block . we can also else block in python to make it executed based on condition.

    95. Will python work multiple inheritance?


    Yes it works by sequentially referring to the parent class one by one.

    96. Will class members be accessible by instances of class?


    Yes by referring corresponding attributes we can access.

    97. What are Special methods in python and how to implement them?


    Special methods in python are __init__,__str__,__iter__,__del__ :

    __init__-it will initialize when class loads.

    __str__-It is used to represent objects in a string format.

    __iter__-it I used to define iteration based on requirements.

    __del__-It is used to destroy objects when it is not required  for memory optimization.

    98. How to handle deadlock in python.


    By providing synchronization methods so that each thread accesses one at a time.It will lock another thread until the thread finds its execution.

    99. How for loop work in python?


    For loop internally calls iter method of an object for each call.

    100. What is List comprehension, how to define it  and when to use?


    List Comprehensions are expression based iteration.

    So we have to give expression and then loop and provide if condition if needed. We have to use when we want to define in such a way that we write the code in a compact way.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free