Best 100 Python Interview Questions & Answers 2021

Table of Contents

Python Interview can be quite difficult.  The questions are divided into groups such as basic, intermediate, and advanced questions. 

Python Questions and Answers provided here are categories in such a way that it helps students and professionals preparing for various Certification Exams and Job Interviews. We have provided here a collection of Python Interview Questions and Python Multiple Choice Questions (MCQs) and their answers with explanations.

Python interview questions


Python MCQ Questions 2021

While using slicing in lists, list[0 2] is equivalent to __.
Select the best answerr from below options :
(1)list[:-2]
(2)list[0:3] -1
(3)list[-2:0]
(4)list[:2]

Answer:-(4)list[:2]

Using Pop in the list will remove the popped up item.
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

What is the output of the following code in Python3?
Select the best answerr from below options :
count = 0
while count < 2:
print (count, ” is less than 2″)
count = count + 2
else:
print (count, ” is not less than 2″)
(1)0 is less than 2; 2 is not less than 2
(2)1 is less than 2; 3 is not less than 2
(3)2 is not less than 2
(4)Error

Answer:-(1)0 is less than 2; 2 is not less than 2

What is the output of bool(5)?
Select the best answerr from below options :
(1)False
(2)0
(3)True
(4)1
(5)Valid

Answer:-(3)True

Which of these packages in Python help with scientific applications of Python?
Select the best answerr from below options :
(1)Pygame and Pysci
(2)MathPy and LabPy
(3)ResearPy and AnalPy
(4)SciPy and NumPy

Answer:-(4)SciPy and NumPy

All of these range types are correct except _.
Select the best answerr from below options :
(1)range(10,20,2)
(2)range(20,40,-1.2)
(3)range(10,20,30)

Answer:-(2)range(20,40,-1.2)

What is the output of the following code in Python 3?
Select the best answerr from below options :
if a:
print(“”””a’s value””””)
else:
print(“”””Sorry nothing will get printed””””)
(1)0
(2)Error
(3)a’s value
(4)Sorry nothing will get printed

Answer:-(2)Error

a.difference(b) highlights the __.
Select the best answerr from below options :
(1)a.union(b) – a.intersection(b)
(2)a.intersection(b) – a.union(b)
(3)a.union(b) – b.intersection(b)
(4)a – b

Answer:-(4)a – b

Which methods can be used with list objects?
Select the best answerr from below options :
(1)Lambda , Pop , Clear
(2)Reverse , Decode, Lambda
(3)Decode , Pop , Clear
(4)Reverse , Decode
(5)Reverse , Pop , Clear

Answer:-(5)Reverse , Pop , Clear

Which statements will result in slice of tuple?
Select the best answerr from below options :
(1)a_tuple[0] =[5] a_tuple[::2]
(2)a_tuple[::2] a_tuple[:]
(3)a_tuple[:] a_tuple[::-1]
(4)a_tuple[::-1] a_tuple[0] =[5]

Answer:-(2)a_tuple[::2] a_tuple[:]

An empty list could be created with the list() alone.
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

What is the output of max(“Infinity”)?
Select the best answerr from below options :
(1)0
(2)f
(3)8
(4)I
(5)y

Answer:-(5)y

Values in bytearray should be integers between _.
Select the best answerr from below options :
(1)0-63
(2)0-255
(3)0-512
(4)0-1024

Answer:-(2)0-255

Which of the following options could be used in the tuple object?
Select the best answerr from below options :
(1)Reverse, Max
(2)Append
(3)Sorted, Lens, Max

Answer:-(1)Reverse, Max

Which statement creates the bytes literal when run?
Select the best answerr from below options :
(1)bytes_literal = bytes.str.count(0x54)
(2)bytes_literal = bytes.encoded.count(0x54)
(3)bytes_literal = bytes(str_literal,’utf-8′)
(4)bytes_literal = b’Copyright \xc2\xa9′

Answer:-(4)bytes_literal = b’Copyright \xc2\xa9′

Byte datatype can contain only _ and _.
Select the best answerr from below options :
(1)ascii & hexadecimal characters
(2)ascii & unicode
(3)unicode alone
(4)decimal & hexadecimal

Answer:-(1)ascii & hexadecimal characters

While using “bool”, all zero values are considered as false and non zero values are considered as true. Is the statement true or false?
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

The bool class is a subset of __.
Select the best answerr from below options :
(1)char
(2)string
(3)long
(4)int
(5)float

Answer:-(4)int

Which is the fastest implementation of Python?
Select the best answerr from below options :
(1)Cpython
(2)Iron Python
(3)Jython
(4)Pypy

Answer:-(4)Pypy

Which describes bytearrays?
Select the best answerr from below options :
(1)Without an argument, an array of size 0 is created; contains a sequence of (2)integers 0-255
(3)Bytearrays are immutable objects

Answer:-(2)integers 0-255

All of these range types are correct except __.
Select the best answerr from below options :
(1)range(20,20,30)
(2)range(20,40,’-2′)
(3)range(20,20,2)
(4)range(20,40,-2)

Answer:-(2)range(20,40,’-2′)

If b is a frozen set, what happens to b.add(3)?
Select the best answerr from below options :
(1)3 will not be available for other general operations
(2)3 will be added as a constant
(3)Error as frozen sets cannot be modified

Answer:-(3)Error as frozen sets cannot be modified

Empty dictionary is represented as __.
Select the best answerr from below options :
(1)()
(2)[]
(3)({})
(4){}

Answer:-(4){}

bytearray provides a mutable sequence, making it modifiable.
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

Equivalent operation for function pow(x, y) is __.
Select the best answerr from below options :
(1)x ^ y
(2)x ** y
(3)x // y
(4)x * y

Answer:-(2)x ** y

Which action must be avoided to prevent the previously defined names from getting overwritten?
Select the best answerr from below options :
(1)Import selective objects
(2)Import selectively with aliases
(3)Using aliases when importing
(4)Use the wildcard import

Answer:-(4)Use the wildcard import

The following options are the salient features of Python except _.
Select the best answerr from below options :
(1)Limited platform support
(2)Open source
(3)Broad standard library
(4)Simple to learn and understand

Answer:-(1)Limited platform support

Which of the following attributes exhibits Pythons characteristics?
Select the best answerr from below options :
(1)Powerful interpreter
(2)Ubiquity
(3)Broad Standard Library
(4)Object-oriented

Answer:-(2)Ubiquity

_ class provides an immutable sequence of elements.
Select the best answerr from below options :
(1)tuple
(2)byte
(3)string
(4)list
(5)bytearray

Answer:-(1)tuple

Which statement correctly assigns X as an infinite number?
Select the best answerr from below options :
(1)x=infinity
(2)x=float(‘inf’)
(3)X=pos_infinity()
(4)x=int(‘inf’)

Answer:-(2)x=float(‘inf’)

What is the output of bool(0)?
Select the best answerr from below options :
(1)Valid
(2)False
(3)True
(4)0
(5)1

Answer:-(2)False

What command is used to output text from both the Python shell and within a Python module?
Select the best answerr from below options :
(1)count()
(2)OutputStream()
(3)print()
(4)System.out.println()
(5)count_print()

Answer:-(3)print()

When using the Python shell and code block, what triggers the interpreter to begin evaluating a block of code?
Select the best answerr from below options :
(1)Blank line
(2)Closed parenthesis
(3)Execute command
(4)Colon symbol
(5)Semi colon symbol

Answer:-(1)Blank line

While using Python IDLE, by how many spaces are the code suites indented?
Select the best answerr from below options :
(1)4
(2)3
(3)5
(4)1
(5)2

Answer:-(1)4

Python is ubiquitous. Is this true or false?
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

While using Python IDLE, by how many spaces are the code suites indented?
Select the best answerr from below options :
(1)4
(2)3
(3)5
(4)1
(5)2

Answer:-(1)4

Python is ubiquitous. Is this true or false?
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

Which statements prevent the escape sequence interpretation?
Select the best answerr from below options :
(1)col1\tcol2\tcol3\t
(2)r’col\tcol2\tcol3\t’
(3)escape’col\tcol2\tcol3\t’
(4)subtext’col\tcol2\tcol3\t’

Answer:-(2)r’col\tcol2\tcol3\t’

What is the output of the following code snippet?
Select the best answerr from below options :
for char in ‘Welcome’:
print (char, end=’‘) print() Select the best answerr from below options : (1)Welcome
(2)Error
(3)Welcome
(4)Welcome

Answer:-(1)Welcome*

a.symmetric_difference(b) highlights the __.
Select the best answerr from below options :
(1)a – b
(2)a.union(b) – b.intersection(b)
(3)a.intersection(b) – a.union(b)
(4)a.union(b) – a.intersection(b)

Answer:-(4)a.union(b) – a.intersection(b)

Is x, y = 5, 6 a valid statement?
Select the best answerr from below options :
(1)True
(2)False

Answer:-(1)True

Which statement accurately defines the bool class?
Select the best answerr from below options :
(1)Boolean first returns False then the True value
(2)Zero values are considered True always
(3)Zero values are considered True some times
(4)Bool class is a subclass of array class
(5)Boolean Not returns False if the operand is True

Answer:-(5)Boolean Not returns False if the operand is True

Which datatype is represented by int in Python 3?
Select the best answerr from below options :
(1)Decimal
(2)Short
(3)float
(4)Long

Answer:-(4)Long

What is the output of min(“Infinity”)?
Select the best answerr from below options :
(1)y
(2)f
(3)0
(4)I

Answer:-(4)I

Python Interview Questions and Answers with Explanation 2021

Q1. What are global, protected and private attributes in Python?
Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.

Protected attributes are attributes defined with a underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

Q2. What are the key features of Python?
Python is an interpreted language. That means that, unlike languages like C and its variants, it does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

it is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x=”I’m a string” without error it is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. it does not have access specifiers (like C++’s public, private).

functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects
Writing code is quick but running it is often slower than compiled languages.

Fortunately,it allows the inclusion of C-based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number-crunching it does isn’t actually done

it finds use in many spheres – web applications, automation, scientific modeling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice.

Q3. What do you understand by lambda function? Create a lambda function which will print the sum of all the elements in this list -> [5, 8, 10, 20, 50, 100]
from functools import reduce
sequences = [5, 8, 10, 20, 50, 100]
sum = reduce (lambda x, y: x+y, sequences)
print(sum)

Q4. How to merge dataframes in pandas?
Merging depends on the type and fields of different dataframes being merged. If data is having similar fields data is merged along axis 0 else they are merged along axis 1.

Q5. What are the built-in types does python provide?
Python has following built-in data types:

Numbers: Python identifies three types of numbers:

Integer: All positive and negative numbers without a fractional part
Float: Any real number with floating-point representation
Complex numbers: A number with a real and imaginary component represented as x+yj. x and y are floats and j is -1(square root of -1 called an imaginary number)
Boolean: The Boolean data type is a data type that has one of two possible values i.e. True or False. Note that ‘T’ and ‘F’ are capital letters.

String: A string value is a collection of one or more characters put in single, double or triple quotes.

List: A list object is an ordered collection of one or more data items which can be of different types, put in square brackets. A list is mutable and thus can be modified, we can add, edit or delete individual elements in a list.

Set: An unordered collection of unique objects enclosed in curly brackets

Frozen set: They are like a set but immutable, which means we cannot modify their values once they are created.

Dictionary: A dictionary object is unordered in which there is a key associated with each value and we can access each value through its key. A collection of such pairs is enclosed in curly brackets. For example {‘First Name’ : ’Tom’ , ’last name’ : ’Hardy’} Note that Number values, strings, and tuple are immutable while as List or Dictionary object are mutable.

Q7. How is memory managed in Python?
Ans: Memory is managed in Python in the following ways:

Memory management is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.

The allocation of heap space of objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.

It also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.

Q8. How to combine dataframes in pandas?
Two different data frames can be stacked either horizontally or vertically by the concat(), append() and join() functions in pandas.

Concat works best when the dataframes have the same columns and can be used for concatenation of data having similar fields and is basically vertical stacking of dataframes into a single dataframe.

Append() is used for horizontal stacking of dataframes. If two tables(dataframes) are to be merged together then this is the best concatenation function.

Join is used when we need to extract data from different dataframes which are having one or more common columns. The stacking is horizontal in this case.

Q9. What is init in Python?
init methodology is a reserved method in Python aka constructor in OOP. When an object is created from a class and init methodolgy is called to acess the class attributes.

Q10. How do you write comments in python?
Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).

Example:

Comments in Python start like this

print(“Comments in Python start with a #”)
Output: Comments in Python start with a #

Q11. What are negative indexes and why are they used?
Ans: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

Q12. What are Python libraries? Name a few of them.
Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.

Q13. What is PEP 8 and why is it important?
PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python Community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing in the Python open-source community requires you to follow these style guidelines sincerely and strictly.

Q14. Define encapsulation in Python?
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.

Q15. What is a dynamically typed language?
Before we understand what a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, “1” + 2 will result in a type error, since these languages don’t allow for “type-coercion” (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output “12” as result.

Type-checking can be done at two stages –

Static – Data Types are checked before execution.
Dynamic – Data Types are checked during execution.
Python being an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed language.

What are decorators in Python?
Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented by the @decorator_name in Python and are called in bottom-up fashion. For example:

decorator function to convert to lowercase

def lowercase_decorator(function):
def wrapper():
func = function()
string_lowercase = func.lower()
return string_lowercase
return wrapper

decorator function to split words

def splitter_decorator(function):
def wrapper():
func = function()
string_split = func.split()
return string_split
return wrapper

@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
return ‘Hello World’

hello() # output => [ ‘hello’ , ‘world’ ]
The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. ‘wrapper’ function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope.

decorator function to capitalize names

def names_decorator(function):
def wrapper(arg1, arg2):
arg1 = arg1.capitalize()
arg2 = arg2.capitalize()
string_hello = function(arg1, arg2)
return string_hello
return wrapper

@names_decorator
def say_hello(name1, name2):
return ‘Hello ‘ + name1 + ‘! Hello ‘ + name2 + ‘!’

say_hello(‘sara’, ‘ansh’) # output => ‘Hello Sara! Hello Ansh!’

Q16. How do you do data abstraction in Python?
Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.

Q17. How do you copy an object in Python?
In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module.

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values are references to other objects, just the reference addresses for the same are copied.
Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

Q18. Write a program in Python to check if a sequence is a Palindrome.

a=input(“enter sequence”)
b=a[::-1]
if a==b:
&amp;amp;amp;nbsp; print(“palindrome”)
else:
&amp;amp;amp;nbsp; print(“Not a Palindrome”)
Output:

enter sequence 323 palindrome

Q19. What is the difference between NumPy and SciPy?
Ans:

In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.

All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.

Thus NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.

If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.

Q20. What are the advantages of Python?

  • Interpreted
  • Free and open source
  • Extensible
  • Object-oriented
  • Built-in data structure
  • Readability
  • High-Level Language
  • Cross-platform

Interpreted: Python is an interpreted language. It does not require prior compilation of code and executes instructions directly.
Free and open source: It is an open source project which is publicly available to reuse. It can be downloaded free of cost.
Portable: Python programs can run on cross platforms without affecting its performance.
Extensible: It is very flexible and extensible with any module.
Object-oriented: Python allows to implement the Object Oriented concepts to build application solution.
Built-in data structure: Tuple, List, and Dictionary are useful integrated data structures provided by the language.

Conclusion

If you are appearing for a technical round of interview for Python Language, here’s a list of the top 100 interview questions with answers to help you prepare.

The first set of Python questions and answers are curated for fresher’s while the second set is designed for advanced users. These Python questions cover all the basic applications of Python and will showcase your expertise in the subject.

Leave a Comment