0% found this document useful (0 votes)
6 views96 pages

Python Interview Questions

Uploaded by

MB Raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views96 pages

Python Interview Questions

Uploaded by

MB Raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Contents

Python Interview Questions for Freshers


1. What is Python? What are the benefits of using Python
2. What is a dynamically typed language?
3. What is an Interpreted language?
4. What is PEP 8 and why is it important?
5. What is Scope in Python?
6. What are lists and tuples? What is the key difference between the two?
7. What are the common built-in data types in Python?
8. What is pass in Python?
9. What are modules and packages in Python?
10. What are global, protected and private attributes in Python?
11. What is the use of self in Python?
12. What is __init__?
13. What is break, continue and pass in Python?
14. What are unit tests in Python?
15. What is docstring in Python?
16. What is slicing in Python?
17. Explain how can you make a Python Script executable on Unix?
18. What is the difference between Python Arrays and lists?

Python Interview Questions for Experienced

Page 1 © Copyright by Interviewbit


Python Interview Questions

Python Interview Questions for


Experienced (.....Continued)

19. How is memory managed in Python?


20. What are Python namespaces? Why are they used?
21. What is Scope Resolution in Python?
22. What are decorators in Python?
23. What are Dict and List comprehensions?
24. What is lambda in Python? Why is it used?
25. How do you copy an object in Python?
26. What is the difference between xrange and range in Python?
27. What is pickling and unpickling?
28. What are generators in Python?
29. What is PYTHONPATH in Python?
30. What is the use of help() and dir() functions?
31. What is the difference between .py and .pyc files?
32. How Python is interpreted?
33. How are arguments passed by value or by reference in python?
34. What are iterators in Python?
35. Explain how to delete a file in Python?
36. Explain split() and join() functions in Python?
37. What does *args and **kwargs mean?
38. What are negative indexes and why are they used?

Page 2 © Copyright by Interviewbit


Python Interview Questions

Python OOPS Interview Questions


39. How do you create a class in Python?
40. How does inheritance work in python? Explain it with an example.
41. How do you access parent members in the child class?
42. Are access specifiers used in python?
43. Is it possible to call parent class without its instance creation?
44. How is an empty class created in python?
45. Differentiate between new and override modifiers.
46. Why is finalize used?
47. What is init method in python?
48. How will you check if a class is a child of another class?

Python Pandas Interview Questions


49. What do you know about pandas?
50. Define pandas dataframe.
51. How will you combine different pandas dataframes?
52. Can you create a series from the dictionary object in pandas?
53. How will you identify and deal with missing values in a dataframe?
54. What do you understand by reindexing in pandas?
55. How to add new column to pandas dataframe?
56. How will you delete indices, rows and columns from a dataframe?

Page 3 © Copyright by Interviewbit


Python Interview Questions

Python Pandas Interview Questions


57. Can you get items of series A that are not available in another series B?
58. How will you get the items that are not common to both the given series A and
B?
59. While importing data from different sources, can the pandas library recognize
dates?

Numpy Interview Questions


60. What do you understand by NumPy?
61. How are NumPy arrays advantageous over python lists?
62. What are the steps to create 1D, 2D and 3D arrays?
63. You are given a numpy array and a new column as inputs. How will you delete
the second column and replace the column with a new column value?
64. How will you efficiently load data from a text file?
65. How will you read CSV data into an array in NumPy?
66. How will you sort the array based on the Nth column?
67. How will you find the nearest value in a given numpy array?
68. How will you reverse the numpy array using one line of code?
69. How will you find the shape of any given NumPy array?

Python Libraries Interview Questions


70. Differentiate between a package and a module in python.
71. What are some of the most commonly used built-in modules in Python?
72. What are lambda functions?
73. How can you generate random numbers?

Page 4 © Copyright by Interviewbit


Python Interview Questions

Python Libraries Interview Questions


74. Can you easily check if all characters in the given string is alphanumeric?
75. What are the differences between pickling and unpickling?
76. Define GIL.
77. Define PYTHONPATH.
78. Define PIP.
79. Are there any tools for identifying bugs and performing static analysis in python?
80. Differentiate between deep and shallow copies.
81. What is main function in python? How do you invoke it?

Python Programming Examples


82. Write python function which takes a variable number of arguments.
83. WAP (Write a program) which takes a sequence of numbers and check if all
numbers are unique.
84. Write a program for counting the number of every character of a given text file.
85. Write a program to check and return the pairs of a given array A whose sum
value is equal to a target value N.
86. Write a Program to add two integers >0 without using the plus operator.
87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are
constants:
88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.
89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy
format.
90. Write a Program to combine two different dictionaries. While combining, if you
find the same keys, you can add the values of these same keys. Output the new
dictionary
91. How will you access the dataset of a publicly shared spreadsheet in CSV format
stored in Google Drive?

Page 5 © Copyright by Interviewbit


Let's get Started

Introduction to Python:

Python was developed by Guido van Rossum and was released first on February 20,
1991. It is one of the most widely-used and loved programming languages and is
interpreted in nature thereby providing flexibility of incorporating dynamic
semantics. It is also a free and open-source language with very simple and clean
syntax. This makes it easy for developers to learn python. Python also supports
object-oriented programming and is most commonly used to perform general-
purpose programming.
Due to its simplistic nature and the ability to achieve multiple functionalities in fewer
lines of code, python’s popularity is growing tremendously. Python is also used in
Machine Learning, Artificial Intelligence, Web Development, Web Scraping, and
various other domains due to its ability to support powerful computations using
powerful libraries. Due to this, there is a huge demand for python developers in India
and across the world. Companies are willing to offer amazing perks and benefits to
these developers.
In this article, we will see the most commonly asked python interview questions and
answers which will help you excel and bag amazing job offers.
We have classified them into the following sections:

Page 6 © Copyright by Interviewbit


Python Interview Questions

Python Interview Questions for Freshers


Python Interview Questions for Experienced
Python OOPS Interview Questions
Python Pandas Interview Questions
Numpy Interview Questions
Python Libraries Interview Questions
Python Programming Examples

Python Cheat Sheet: Basic to Advanced Concepts

Python Interview Questions for Freshers


1. What is Python? What are the benefits of using Python
Python is a high-level, interpreted, general-purpose programming language. Being a
general-purpose language, it can be used to build almost any type of application with
the right tools/libraries. Additionally, python supports objects, modules, threads,
exception-handling, and automatic memory management which help in modelling
real-world problems and building applications to solve these problems.

Page 7 © Copyright by Interviewbit


Python Interview Questions

Benefits of using Python:


Python is a general-purpose programming language that has a simple, easy-to-
learn syntax that emphasizes readability and therefore reduces the cost of
program maintenance. Moreover, the language is capable of scripting, is
completely open-source, and supports third-party packages encouraging
modularity and code reuse.
Its high-level data structures, combined with dynamic typing and dynamic
binding, attract a huge community of developers for Rapid Application
Development and deployment.

2. What is a dynamically typed language?


Before we understand 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 is 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.

Page 8 © Copyright by Interviewbit


Python Interview Questions

3. What is an Interpreted language?


An Interpreted language executes its statements line by line. Languages such as
Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages.
Programs written in an interpreted language runs directly from the source code, with
no intermediary compilation step.

4. 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 to the Python open-source
community requires you to follow these style guidelines sincerely and strictly.

5. What is Scope in Python?


Every object in Python functions within a scope. A scope is a block of code where an
object in Python remains relevant. Namespaces uniquely identify all the objects
inside a program. However, these namespaces also have a scope defined for them
where you could use their objects without any prefix. A few examples of scope
created during code execution in Python are as follows:

Page 9 © Copyright by Interviewbit


Python Interview Questions

A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution
since their inception.
A module-level scope refers to the global objects of the current module
accessible in the program.
An outermost scope refers to all the built-in names callable in the program. The
objects in this scope are searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords
such as global.

6. What are lists and tuples? What is the key difference between
the two?
Lists and Tuples are both sequence data types that can store a collection of objects
in Python. The objects stored in both sequences can have different data types. Lists
are represented with square brackets ['sara', 6, 0.19] , while tuples are
represented with parantheses ('ansh', 5, 0.97) .
But what is the real difference between the two? The key difference between the two
is that while lists are mutable, tuples on the other hand are immutable objects.
This means that lists can be modified, appended or sliced on the go but tuples
remain constant and cannot be modified in any manner. You can run the following
example on Python IDLE to confirm the difference:

my_tuple = ('sara', 6, 5, 0.97)


my_list = ['sara', 6, 5, 0.97]
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'sara'
my_tuple[0] = 'ansh' # modifying tuple => throws an error
my_list[0] = 'ansh' # modifying list => list modified
print(my_tuple[0]) # output => 'sara'
print(my_list[0]) # output => 'ansh'

7. What are the common built-in data types in Python?

Page 10 © Copyright by Interviewbit


Python Interview Questions

There are several built-in data types in Python. Although, Python doesn't require data
types to be defined explicitly during variable declarations type errors are likely to
occur if the knowledge of data types and their compatibility with each other are
neglected. Python provides type() and isinstance() functions to check the type
of these variables. These data types can be grouped into the following categories-
None Type:
None keyword represents the null values in Python. Boolean equality
operation can be performed using these NoneType objects.

Class Name Description

NoneType Represents the NULL values in Python.

Numeric Types:
There are three distinct numeric types - integers, floating-point numbers, and
complex numbers. Additionally, booleans are a sub-type of integers.

Class Name Description

Stores integer literals including hex, octal and


int
binary numbers as integers

Stores literals containing decimal values


float and/or exponent signs as floating-point
numbers

Stores complex numbers in the form (A + Bj)


complex
and has attributes: real and imag

bool Stores boolean value (True or False).

Page 11 © Copyright by Interviewbit


Python Interview Questions

Note: The standard library also includes fractions to store rational numbers and
decimal to store floating-point numbers with user-defined precision.
Sequence Types:
According to Python Docs, there are three basic Sequence Types - lists, tuples,
and range objects. Sequence types have the in and not in operators
defined for their traversing their elements. These operators share the same
priority as the comparison operations.

Class Name Description

Mutable sequence used to store collection of


list
items.

Immutable sequence used to store collection


tuple
of items.

Represents an immutable sequence of


range
numbers generated during execution.

Immutable sequence of Unicode code points


str
to store textual data.

Note: The standard library also includes additional types for processing:
1. Binary data such as bytearray bytes memoryview , and
2. Text strings such as str .
Mapping Types:
A mapping object can map hashable values to random objects in Python. Mappings
objects are mutable and there is currently only one standard mapping type, the
dictionary.

Page 12 © Copyright by Interviewbit


Python Interview Questions

Class Name Description

Stores comma-separated list of key: value


dict
pairs

Set Types:
Currently, Python has two built-in set types - set and frozenset. set type is
mutable and supports methods like add() and remove() . frozenset type is
immutable and can't be modified a er creation.

Class Name Description

Mutable unordered collection of distinct


set
hashable objects.

Immutable collection of distinct hashable


frozenset
objects.

Note: set is mutable and thus cannot be used as key for a dictionary. On the other
hand, frozenset is immutable and thus, hashable, and can be used as a dictionary
key or as an element of another set.

Page 13 © Copyright by Interviewbit


Python Interview Questions

Modules:
Module is an additional built-in type supported by the Python Interpreter. It
supports one special operation, i.e., attribute access: mymod.myobj , where
mymod is a module and myobj references a name defined in m's symbol table.
The module's symbol table resides in a very special attribute of the module
__dict__, but direct assignment to this module is neither possible nor
recommended.
Callable Types:
Callable types are the types to which function call can be applied. They can be
user-defined functions, instance methods, generator functions, and some
other built-in functions, methods and classes.
Refer to the documentation at docs.python.org for a detailed view of the
callable types.

8. What is pass in Python?


The pass keyword represents a null operation in Python. It is generally used for
the purpose of filling up empty blocks of code which may execute during runtime but
has yet to be written. Without the pass statement in the following code, we may run
into some errors during code execution.

def myEmptyFunc():
# do nothing
pass
myEmptyFunc() # nothing happens
## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block

9. What are modules and packages in Python?


Python packages and Python modules are two mechanisms that allow for modular
programming in Python. Modularizing has several advantages -

Page 14 © Copyright by Interviewbit


Python Interview Questions

Simplicity: Working on a single module helps you focus on a relatively small


portion of the problem at hand. This makes development easier and less error-
prone.
Maintainability: Modules are designed to enforce logical boundaries between
different problem domains. If they are written in a manner that reduces
interdependency, it is less likely that modifications in a module might impact
other parts of the program.
Reusability: Functions defined in a module can be easily reused by other parts
of the application.
Scoping: Modules typically define a separate namespace, which helps avoid
confusion between identifiers from other parts of the program.
Modules, in general, are simply Python files with a .py extension and can have a set of
functions, classes, or variables defined and implemented. They can be imported and
initialized once using the import statement. If partial functionality is needed,
import the requisite classes or functions using from foo import bar .
Packages allow for hierarchial structuring of the module namespace using dot
notation. As, modules help avoid clashes between global variable names, in a similar
manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system's inherent file structure.
So just stuff the modules into a folder and there you have it, the folder name as the
package name. Importing a module or its contents from this package requires the
package name as prefix to the module name joined by a dot.
Note: You can technically import the package as well, but alas, it doesn't import the
modules within the package to the local namespace, thus, it is practically useless.

10. What are global, protected and private attributes in


Python?

Page 15 © Copyright by Interviewbit


Python Interview Questions

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 an 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.

11. What is the use of self in Python?


Self is used to represent the instance of the class. With this keyword, you can access
the attributes and methods of the class in python. It binds the attributes with the
given arguments. self is used in different places and o en thought to be a keyword.
But unlike in C++, self is not a keyword in Python.

12. What is __init__?


__init__ is a contructor method in Python and is automatically called to allocate
memory when a new object/instance is created. All classes have a __init__ method
associated with them. It helps in distinguishing methods and attributes of a class
from local variables.

# class definition
class Student:
def __init__(self, fname, lname, age, section):
self.firstname = fname
self.lastname = lname
self.age = age
self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")

13. What is break, continue and pass in Python?

Page 16 © Copyright by Interviewbit


Python Interview Questions

Break The break statement terminates the loop


immediately and the control flows to the
statement a er the body of the loop.

Continue The continue statement terminates the current


iteration of the statement, skips the rest of the
code in the current iteration and the control
flows to the next iteration of the loop.

Pass As explained above, the pass keyword in Python


is generally used to fill up empty blocks and is
similar to an empty statement represented by a
semi-colon in languages such as Java, C++,
Javascript, etc.

pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
pass
if (p == 0):
current = p
break
elif (p % 2 == 0):
continue
print(p) # output => 1 3 1 3 1
print(current) # output => 0

14. What are unit tests in Python?

Page 17 © Copyright by Interviewbit


Python Interview Questions

Unit test is a unit testing framework of Python.


Unit testing means testing different components of so ware separately. Can you
think about why unit testing is important? Imagine a scenario, you are building
so ware that uses three components namely A, B, and C. Now, suppose your
so ware breaks at a point time. How will you find which component was
responsible for breaking the so ware? Maybe it was component A that failed,
which in turn failed component B, and this actually failed the so ware. There
can be many such combinations.
This is why it is necessary to test each and every component properly so that we
know which component might be highly responsible for the failure of the
so ware.

15. What is docstring in Python?


Documentation string or docstring is a multiline string used to document a
specific code segment.
The docstring should describe what the function or method does.

16. What is slicing in Python?


As the name suggests, ‘slicing’ is taking parts of.
Syntax for slicing is [start : stop : step]
start is the starting index from where to slice a list or tuple
stop is the ending index or where to sop.
step is the number of steps to jump.
Default value for start is 0, stop is number of items, step is 1.
Slicing can be done on strings, arrays, lists, and tuples.

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


print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]

17. Explain how can you make a Python Script executable on


Unix?
Script file must begin with #!/usr/bin/env python

18. What is the difference between Python Arrays and lists?

Page 18 © Copyright by Interviewbit


Python Interview Questions

Arrays in python can only contain elements of same data types i.e., data type of
array should be homogeneous. It is a thin wrapper around C language arrays and
consumes far less memory than lists.
Lists in python can contain elements of different data types i.e., data type of lists
can be heterogeneous. It has the disadvantage of consuming large memory.

import array
a = array.array('i', [1, 2, 3])
for i in a:
print(i, end=' ') #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (g
a = [1, 2, 'string']
for i in a:
print(i, end=' ') #OUTPUT: 1 2 string

Python Interview Questions for Experienced


19. How is memory managed in Python?
Memory management in Python is handled by the Python Memory Manager.
The memory allocated by the manager is in form of a private heap space
dedicated to Python. All Python objects are stored in this heap and being
private, it is inaccessible to the programmer. Though, python does provide some
core API functions to work upon the private heap space.
Additionally, Python has an in-built garbage collection to recycle the unused
memory for the private heap space.

Page 19 © Copyright by Interviewbit


Python Interview Questions

20. What are Python namespaces? Why are they used?


A namespace in Python ensures that object names in a program are unique and can
be used without any conflict. Python implements these namespaces as dictionaries
with 'name as key' mapped to a corresponding 'object as value'. This allows for
multiple namespaces to use the same name and map it to a separate object. A few
examples of namespaces are as follows:
Local Namespace includes local names inside a function. the namespace is
temporarily created for a function call and gets cleared when the function
returns.
Global Namespace includes names from various imported packages/ modules
that are being used in the current project. This namespace is created when the
package is imported in the script and lasts until the execution of the script.
Built-in Namespace includes built-in functions of core Python and built-in
names for various types of exceptions.
The lifecycle of a namespace depends upon the scope of objects they are mapped
to. If the scope of an object ends, the lifecycle of that namespace comes to an end.
Hence, it isn't possible to access inner namespace objects from an outer namespace.

Page 20 © Copyright by Interviewbit


Python Interview Questions

21. What is Scope Resolution in Python?


Sometimes objects within the same scope have the same name but function
differently. In such cases, scope resolution comes into play in Python automatically. A
few examples of such behavior are:
Python modules namely 'math' and 'cmath' have a lot of functions that are
common to both of them - log10() , acos() , exp() etc. To resolve this
ambiguity, it is necessary to prefix them with their respective module, like
math.exp() and cmath.exp() .
Consider the code below, an object temp has been initialized to 10 globally and
then to 20 on function call. However, the function call didn't change the value of
the temp globally. Here, we can observe that Python draws a clear line between
global and local variables, treating their namespaces as separate identities.

Page 21 © Copyright by Interviewbit


Python Interview Questions

temp = 10 # global-scope variable


def func():
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 10

This behavior can be overridden using the global keyword inside the function, as
shown in the following example:

temp = 10 # global-scope variable


def func():
global temp
temp = 20 # local-scope variable
print(temp)
print(temp) # output => 10
func() # output => 20
print(temp) # output => 20

22. 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 the @decorator_name in Python and are called in a bottom-up fashion.
For example:

Page 22 © Copyright by Interviewbit


Python Interview Questions

# 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!'

23. What are Dict and List comprehensions?

Page 23 © Copyright by Interviewbit


Python Interview Questions

Python comprehensions, like decorators, are syntactic sugar constructs that help
build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or
set. Using comprehensions saves a lot of time and code that might be considerably
more verbose (containing more lines of code). Let's check out some examples, where
comprehensions can be truly beneficial:
Performing mathematical operations on the entire list

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}

Performing conditional filtering operations on the entire list

my_list = [2, 3, 5, 7, 11]


squared_list = [x**2 for x in my_list if x%2 != 0] # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0} # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one


Comprehensions allow for multiple iterators and hence, can be used to combine
multiple lists into one.

a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)] # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b] # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)]

Flattening a multi-dimensional list


A similar approach of nested iterators (as above) can be applied to flatten a multi-
dimensional list or work upon its inner elements.

Page 24 © Copyright by Interviewbit


Python Interview Questions

my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

Note: List comprehensions have the same effect as the map method in other
languages. They follow the mathematical set builder notation rather than map
and filter functions in Python.

24. What is lambda in Python? Why is it used?


Lambda is an anonymous function in Python, that can accept any number of
arguments, but can only have a single expression. It is generally used in situations
requiring an anonymous function for a short time period. Lambda functions can be
used in either of the two ways:
Assigning lambda functions to a variable:

mul = lambda a, b : a * b
print(mul(2, 5)) # output => 10

Wrapping lambda functions inside another function:

def myWrapper(n):
return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2)) # output => 10

25. 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 -

Page 25 © Copyright by Interviewbit


Python Interview Questions

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 is a reference 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.

from copy import copy, deepcopy


list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
list_2 # output => [1, 2, [3, 5, 6], 7]
list_1 # output => [1, 2, [3, 5, 6], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3 # output => [1, 2, [3, 5, 6, 7], 8]
list_1 # output => [1, 2, [3, 5, 6], 4]

26. What is the difference between xrange and range in Python?


xrange() and range() are quite similar in terms of functionality. They both generate a
sequence of integers, with the only difference that range() returns a Python list,
whereas, xrange() returns an xrange object.
So how does that make a difference? It sure does, because unlike range(), xrange()
doesn't generate a static list, it creates the value on the go. This technique is
commonly used with an object-type generator and has been termed as "yielding".
Yielding is crucial in applications where memory is a constraint. Creating a static list
as in range() can lead to a Memory Error in such conditions, while, xrange() can
handle it optimally by using just enough memory for the generator (significantly less
in comparison).

Page 26 © Copyright by Interviewbit


Python Interview Questions

for i in xrange(10): # numbers from o to 9


print i # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10): # numbers from 1 to 9
print i # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2): # skip by two for next
print i # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range does exactly the
same as what xrange used to do in Python 2.x, since it was way better to use
xrange() than the original range() function in Python 2.x.

27. What is pickling and unpickling?


Python library offers a feature - serialization out of the box. Serializing an object
refers to transforming it into a format that can be stored, so as to be able to
deserialize it, later on, to obtain the original object. Here, the pickle module comes
into play.
Pickling:
Pickling is the name of the serialization process in Python. Any object in Python
can be serialized into a byte stream and dumped as a file in the memory. The
process of pickling is compact but pickle objects can be compressed further.
Moreover, pickle keeps track of the objects it has serialized and the serialization
is portable across versions.
The function used for the above process is pickle.dump() .
Unpickling:
Unpickling is the complete inverse of pickling. It deserializes the byte stream to
recreate the objects stored in the file and loads the object to memory.
The function used for the above process is pickle.load() .
Note: Python has another, more primitive, serialization module called marshall,
which exists primarily to support .pyc files in Python and differs significantly from
the pickle.

Page 27 © Copyright by Interviewbit


Python Interview Questions

28. What are generators in Python?


Generators are functions that return an iterable collection of items, one at a time, in
a set manner. Generators, in general, are used to create iterators with a different
approach. They employ the use of yield keyword rather than return to return a
generator object.
Let's try and build a generator for fibonacci numbers -

Page 28 © Copyright by Interviewbit


Python Interview Questions

## generate fibonacci numbers upto n


def fib(n):
p, q = 0, 1
while(p < n):
yield p
p, q = q, p + q
x = fib(10) # create generator object

## iterating using __next__(), for Python2, use next()


x.__next__() # output => 0
x.__next__() # output => 1
x.__next__() # output => 1
x.__next__() # output => 2
x.__next__() # output => 3
x.__next__() # output => 5
x.__next__() # output => 8
x.__next__() # error

## iterating using loop


for i in fib(10):
print(i) # output => 0 1 1 2 3 5 8

29. What is PYTHONPATH in Python?


PYTHONPATH is an environment variable which you can set to add additional
directories where Python will look for modules and packages. This is especially useful
in maintaining Python libraries that you do not wish to install in the global default
location.

30. What is the use of help() and dir() functions?


help() function in Python is used to display the documentation of modules, classes,
functions, keywords, etc. If no parameter is passed to the help() function, then an
interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is
called upon. It behaves differently with different objects, as it aims to produce the
most relevant data, rather than the complete information.
For Modules/Library objects, it returns a list of all attributes, contained in that
module.
For Class Objects, it returns a list of all valid attributes and base attributes.
With no arguments passed, it returns a list of attributes in the current scope.

Page 29 © Copyright by Interviewbit


Python Interview Questions

31. What is the difference between .py and .pyc files?


.py files contain the source code of a program. Whereas, .pyc file contains the
bytecode of your program. We get bytecode a er compilation of .py file (source
code). .pyc files are not created for all the files that you run. It is only created for
the files that you import.
Before executing a python program python interpreter checks for the compiled
files. If the file is present, the virtual machine executes it. If not found, it checks
for .py file. If found, compiles it to .pyc file and then python virtual machine
executes it.
Having .pyc file saves you the compilation time.

32. How Python is interpreted?


Python as a language is not interpreted or compiled. Interpreted or compiled is
the property of the implementation. Python is a bytecode(set of interpreter
readable instructions) interpreted generally.
Source code is a file with .py extension.
Python compiles the source code to a set of instructions for a virtual machine.
The Python interpreter is an implementation of that virtual machine. This
intermediate format is called “bytecode”.
.py source code is first compiled to give .pyc which is bytecode. This bytecode
can be then interpreted by the official CPython or JIT(Just in Time compiler)
compiled by PyPy.

33. How are arguments passed by value or by reference in


python?
Pass by value: Copy of the actual object is passed. Changing the value of the
copy of the object will not change the value of the original object.
Pass by reference: Reference to the actual object is passed. Changing the value
of the new object will change the value of the original object.
In Python, arguments are passed by reference, i.e., reference to the actual object is
passed.

Page 30 © Copyright by Interviewbit


Python Interview Questions

def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
print(arr) #Output: => [1, 2, 3]
appendNumber(arr)
print(arr) #Output: => [1, 2, 3, 4]

34. What are iterators in Python?


An iterator is an object.
It remembers its state i.e., where it is during iteration (see code below to see
how)
__iter__() method initializes an iterator.
It has a __next__() method which returns the next item in iteration and points to
the next element. Upon reaching the end of iterable object __next__() must
return StopIteration exception.
It is also self-iterable.
Iterators are objects with which we can iterate over iterable objects like lists,
strings, etc.

class ArrayList:
def __init__(self, number_list):
self.numbers = number_list
def __iter__(self):
self.pos = 0
return self
def __next__(self):
if(self.pos < len(self.numbers)):
self.pos += 1
return self.numbers[self.pos - 1]
else:
raise StopIteration
array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it)) #output: 2
print(next(it)) #output: 3
print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration

Page 31 © Copyright by Interviewbit


Python Interview Questions

35. Explain how to delete a file in Python?


Use command os.remove(file_name)

import os
os.remove("ChangedFile.csv")
print("File Removed!")

36. Explain split() and join() functions in Python?


You can use split() function to split a string based on a delimiter to a list of
strings.
You can use join() function to join a list of strings based on a delimiter to give a
single string.

string = "This is a string."


string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.

37. What does *args and **kwargs mean?


*args
*args is a special syntax used in the function definition to pass variable-length
arguments.
“*” means variable length and “args” is the name used by convention. You can
use any other.

def multiply(a, b, *argv):


mul = a * b
for num in argv:
mul *= num
return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

Page 32 © Copyright by Interviewbit


Python Interview Questions

**kwargs is a special syntax used in the function definition to pass variable-


length keyworded arguments.
Here, also, “kwargs” is used just by convention. You can use any other name.
Keyworded argument means a variable that has a name when passed to a
function.
It is actually a dictionary of the variable names and its value.

def tellArguments(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

38. What are negative indexes and why are they used?
Negative indexes are the indexes from the end of the list or tuple or string.
Arr[-1] means the last element of array Arr[]

arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5

Python OOPS Interview Questions


39. How do you create a class in Python?
To create a class in python, we use the keyword “class” as shown in the example
below:

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

To instantiate or create an object from the class created above, we do the following:

Page 33 © Copyright by Interviewbit


Python Interview Questions

emp_1=InterviewbitEmployee("Mr. Employee")

To access the name attribute, we just call the attribute using the dot operator as
shown below:

print(emp_1.emp_name)
# Prints Mr. Employee

To create methods inside the class, we include the methods under the scope of the
class as shown below:

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

def introduce(self):
print("Hello I am " + self.emp_name)

The self parameter in the init and introduce functions represent the reference to the
current class instance which is used for accessing attributes and methods of that
class. The self parameter has to be the first parameter of any method defined inside
the class. The method of the class InterviewbitEmployee can be accessed as shown
below:

emp_1.introduce()

The overall program would look like this:

Page 34 © Copyright by Interviewbit


Python Interview Questions

class InterviewbitEmployee:
def __init__(self, emp_name):
self.emp_name = emp_name

def introduce(self):
print("Hello I am " + self.emp_name)

# create an object of InterviewbitEmployee class


emp_1 = InterviewbitEmployee("Mr Employee")
print(emp_1.emp_name) #print employee name
emp_1.introduce() #introduce the employee

40. How does inheritance work in python? Explain it with an


example.
Inheritance gives the power to a class to access all attributes and methods of another
class. It aids in code reusability and helps the developer to maintain applications
without redundant code. The class inheriting from another class is a child class or
also called a derived class. The class from which a child class derives the members are
called parent class or superclass.
Python supports different kinds of inheritance, they are:
Single Inheritance: Child class derives members of one parent class.

Page 35 © Copyright by Interviewbit


Python Interview Questions

# Parent class
class ParentClass:
def par_func(self):
print("I am parent class function")

# Child class
class ChildClass(ParentClass):
def child_func(self):
print("I am child class function")

# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()

Multi-level Inheritance: The members of the parent class, A, are inherited by


child class which is then inherited by another child class, B. The features of the
base class and the derived class are further inherited into the new derived class,
C. Here, A is the grandfather class of class C.

Page 36 © Copyright by Interviewbit


Python Interview Questions

Page 37 © Copyright by Interviewbit


Python Interview Questions

# Parent class
class A:
def __init__(self, a_name):
self.a_name = a_name

# Intermediate class
class B(A):
def __init__(self, b_name, a_name):
self.b_name = b_name
# invoke constructor of class A
A.__init__(self, a_name)

# Child class
class C(B):
def __init__(self,c_name, b_name, a_name):
self.c_name = c_name
# invoke constructor of class B
B.__init__(self, b_name, a_name)

def display_names(self):
print("A name : ", self.a_name)
print("B name : ", self.b_name)
print("C name : ", self.c_name)

# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()

Multiple Inheritance: This is achieved when one child class derives members
from more than one parent class. All features of parent classes are inherited in
the child class.

Page 38 © Copyright by Interviewbit


Python Interview Questions

# Parent class1
class Parent1:
def parent1_func(self):
print("Hi I am first Parent")

# Parent class2
class Parent2:
def parent2_func(self):
print("Hi I am second Parent")

# Child class
class Child(Parent1, Parent2):
def child_func(self):
self.parent1_func()
self.parent2_func()

# Driver's code
obj1 = Child()
obj1.child_func()

Hierarchical Inheritance: When a parent class is derived by more than one child
class, it is called hierarchical inheritance.

Page 39 © Copyright by Interviewbit


Python Interview Questions

# Base class
class A:
def a_func(self):
print("I am from the parent class.")

# 1st Derived class


class B(A):
def b_func(self):
print("I am from the first child.")

# 2nd Derived class


class C(A):
def c_func(self):
print("I am from the second child.")

# Driver's code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func() #child 1 method
obj2.a_func()
obj2.c_func() #child 2 method

41. How do you access parent members in the child class?

Page 40 © Copyright by Interviewbit


Python Interview Questions

Following are the ways using which you can access parent class members within a
child class:
By using Parent class name: You can use the name of the parent class to access
the attributes as shown in the example below:

class Parent(object):
# Constructor
def __init__(self, name):
self.name = name

class Child(Parent):
# Constructor
def __init__(self, name, age):
Parent.name = name
self.age = age

def display(self):
print(Parent.name, self.age)

# Driver Code
obj = Child("Interviewbit", 6)
obj.display()

By using super(): The parent class members can be accessed in child class using
the super keyword.

Page 41 © Copyright by Interviewbit


Python Interview Questions

class Parent(object):
# Constructor
def __init__(self, name):
self.name = name

class Child(Parent):
# Constructor
def __init__(self, name, age):
'''
In Python 3.x, we can also use super().__init__(name)
'''
super(Child, self).__init__(name)
self.age = age

def display(self):
# Note that Parent.name cant be used
# here since super() is used in the constructor
print(self.name, self.age)

# Driver Code
obj = Child("Interviewbit", 6)
obj.display()

42. Are access specifiers used in python?


Python does not make use of access specifiers specifically like private, public,
protected, etc. However, it does not derive this from any variables. It has the concept
of imitating the behaviour of variables by making use of a single (protected) or
double underscore (private) as prefixed to the variable names. By default, the
variables without prefixed underscores are public.
Example:

Page 42 © Copyright by Interviewbit


Python Interview Questions

# to demonstrate access specifiers


class InterviewbitEmployee:

# protected members
_emp_name = None
_age = None

# private members
__branch = None

# constructor
def __init__(self, emp_name, age, branch):
self._emp_name = emp_name
self._age = age
self.__branch = branch

#public member
def display():
print(self._emp_name +" "+self._age+" "+self.__branch)

43. Is it possible to call parent class without its instance


creation?
Yes, it is possible if the base class is instantiated by other child classes or if the base
class is a static method.

44. How is an empty class created in python?


An empty class does not have any members defined in it. It is created by using the
pass keyword (the pass command does nothing in python). We can create objects for
this class outside the class.
For example-

class EmptyClassDemo:
pass
obj=EmptyClassDemo()
obj.name="Interviewbit"
print("Name created= ",obj.name)

Output:
Name created = Interviewbit

Page 43 © Copyright by Interviewbit


Python Interview Questions

45. Differentiate between new and override modifiers.


The new modifier is used to instruct the compiler to use the new implementation
and not the base class function. The Override modifier is useful for overriding a base
class function inside the child class.

46. Why is finalize used?


Finalize method is used for freeing up the unmanaged resources and clean up before
the garbage collection method is invoked. This helps in performing memory
management tasks.

47. What is init method in python?


The init method works similarly to the constructors in Java. The method is run as
soon as an object is instantiated. It is useful for initializing any attributes or default
behaviour of the object at the time of instantiation.
For example:

class InterviewbitEmployee:

# init method / constructor


def __init__(self, emp_name):
self.emp_name = emp_name

# introduce method
def introduce(self):
print('Hello, I am ', self.emp_name)

emp = InterviewbitEmployee('Mr Employee') # __init__ method is called here and initi


emp.introduce()

48. How will you check if a class is a child of another class?


This is done by using a method called issubclass() provided by python. The method
tells us if any class is a child of another class by returning true or false accordingly.
For example:

Page 44 © Copyright by Interviewbit


Python Interview Questions

class Parent(object):
pass

class Child(Parent):
pass

# Driver Code
print(issubclass(Child, Parent)) #True
print(issubclass(Parent, Child)) #False

We can check if an object is an instance of a class by making use of isinstance()


method:

obj1 = Child()
obj2 = Parent()
print(isinstance(obj2, Child)) #False
print(isinstance(obj2, Parent)) #True

Python Pandas Interview Questions


49. What do you know about pandas?
Pandas is an open-source, python-based library used in data manipulation
applications requiring high performance. The name is derived from “Panel Data”
having multidimensional data. This was developed in 2008 by Wes McKinney and
was developed for data analysis.
Pandas are useful in performing 5 major steps of data analysis - Load the data,
clean/manipulate it, prepare it, model it, and analyze the data.

50. Define pandas dataframe.


A dataframe is a 2D mutable and tabular structure for representing data labelled with
axes - rows and columns.
The syntax for creating dataframe:

import pandas as pd
dataframe = pd.DataFrame( data, index, columns, dtype)

where:

Page 45 © Copyright by Interviewbit


Python Interview Questions

data - Represents various forms like series, map, ndarray, lists, dict etc.
index - Optional argument that represents an index to row labels.
columns - Optional argument for column labels.
Dtype - the data type of each column. Again optional.

51. How will you combine different pandas dataframes?


The dataframes can be combines using the below approaches:
append() method: This is used to stack the dataframes horizontally. Syntax:

df1.append(df2)

concat() method: This is used to stack dataframes vertically. This is best used
when the dataframes have the same columns and similar fields. Syntax:

pd.concat([df1, df2])

join() method: This is used for extracting data from various dataframes having
one or more common columns.

df1.join(df2)

52. Can you create a series from the dictionary object in


pandas?
One dimensional array capable of storing different data types is called a series. We
can create pandas series from a dictionary object as shown below:

Page 46 © Copyright by Interviewbit


Python Interview Questions

import pandas as pd
dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2}
series_obj = pd.Series(dict_info)
print (series_obj)
Output:
x 2.0
y 3.1
z 2.2
dtype: float64

If an index is not specified in the input method, then the keys of the dictionaries are
sorted in ascending order for constructing the index. In case the index is passed, then
values of the index label will be extracted from the dictionary.

53. How will you identify and deal with missing values in a
dataframe?
We can identify if a dataframe has missing values by using the isnull() and isna()
methods.

missing_data_count=df.isnull().sum()

We can handle missing values by either replacing the values in the column with 0 as
follows:

df[‘column_name’].fillna(0)

Or by replacing it with the mean value of the column

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

54. What do you understand by reindexing in pandas?

Page 47 © Copyright by Interviewbit


Python Interview Questions

Reindexing is the process of conforming a dataframe to a new index with optional


filling logic. If the values are missing in the previous index, then NaN/NA is placed in
the location. A new object is returned unless a new index is produced that is
equivalent to the current one. The copy value is set to False. This is also used for
changing the index of rows and columns in the dataframe.

55. How to add new column to pandas dataframe?


A new column can be added to a pandas dataframe as follows:

import pandas as pd
data_info = {'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_info)
#To add new column third
df['third']=pd.Series([10,20,30],index=['a','b','c'])
print (df)
#To add new column fourth
df['fourth']=df['first']+info['third']
print (df)

56. How will you delete indices, rows and columns from a
dataframe?
To delete an Index:
Execute del df.index.name for removing the index by name.
Alternatively, the df.index.name can be assigned to None.
For example, if you have the below dataframe:

Column 1
Names
John 1
Jack 2
Judy 3
Jim 4

To drop the index name “Names”:

Page 48 © Copyright by Interviewbit


Python Interview Questions

df.index.name = None
# Or run the below:
# del df.index.name
print(df)
Column 1
John 1
Jack 2
Judy 3
Jim 4

To delete row/column from dataframe:


drop()method is used to delete row/column from dataframe.
The axis argument is passed to the drop method where if the value is 0, it
indicates to drop/delete a row and if 1 it has to drop the column.
Additionally, we can try to delete the rows/columns in place by setting the value
of inplace to True. This makes sure that the job is done without the need for
reassignment.
The duplicate values from the row/column can be deleted by using the
drop_duplicates() method.

Page 49 © Copyright by Interviewbit


Python Interview Questions

57. Can you get items of series A that are not available in
another series B?
This can be achieved by using the ~ (not/negation symbol) and isin() method
as shown below.

import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1=df1[~df1.isin(df2)]
print(df1)
"""
Output:
0 2
1 4
dtype: int64
"""

58. How will you get the items that are not common to both the
given series A and B?
We can achieve this by first performing the union of both series, then taking the
intersection of both series. Then we follow the approach of getting items of union
that are not there in the list of the intersection.

Page 50 © Copyright by Interviewbit


Python Interview Questions

The following code demonstrates this:

import pandas as pd
import numpy as np
df1 = pd.Series([2, 4, 5, 8, 10])
df2 = pd.Series([8, 10, 13, 15, 17])
p_union = pd.Series(np.union1d(df1, df2)) # union of series
p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series
unique_elements = p_union[~p_union.isin(p_intersect)]
print(unique_elements)
"""
Output:
0 2
1 4
2 5
5 13
6 15
7 17
dtype: int64
"""

59. While importing data from different sources, can the pandas
library recognize dates?

Page 51 © Copyright by Interviewbit


Python Interview Questions

Yes, they can, but with some bit of help. We need to add the parse_dates argument
while we are reading data from the sources. Consider an example where we read data
from a CSV file, we may encounter different date-time formats that are not readable
by the pandas library. In this case, pandas provide flexibility to build our custom date
parser with the help of lambda functions as shown below:

import pandas as pd
from datetime import datetime
dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=datepars

Numpy Interview Questions


60. What do you understand by NumPy?
NumPy is one of the most popular, easy-to-use, versatile, open-source, python-based,
general-purpose package that is used for processing arrays. NumPy is short for
NUMerical PYthon. This is very famous for its highly optimized tools that result in
high performance and powerful N-Dimensional array processing feature that is
designed explicitly to work on complex arrays. Due to its popularity and powerful
performance and its flexibility to perform various operations like trigonometric
operations, algebraic and statistical computations, it is most commonly used in
performing scientific computations and various broadcasting functions. The
following image shows the applications of NumPy:

Page 52 © Copyright by Interviewbit


Python Interview Questions

61. How are NumPy arrays advantageous over python lists?


The list data structure of python is very highly efficient and is capable of
performing various functions. But, they have severe limitations when it comes to
the computation of vectorized operations which deals with element-wise
multiplication and addition. The python lists also require the information
regarding the type of every element which results in overhead as type
dispatching code gets executes every time any operation is performed on any
element. This is where the NumPy arrays come into the picture as all the
limitations of python lists are handled in NumPy arrays.
Additionally, as the size of the NumPy arrays increases, NumPy becomes around
30x times faster than the Python List. This is because the Numpy arrays are
densely packed in the memory due to their homogenous nature. This ensures
the memory free up is also faster.

62. What are the steps to create 1D, 2D and 3D arrays?


1D array creation:

Page 53 © Copyright by Interviewbit


Python Interview Questions

import numpy as np
one_dimensional_list = [1,2,4]
one_dimensional_arr = np.array(one_dimensional_list)
print("1D array is : ",one_dimensional_arr)

2D array creation:

import numpy as np
two_dimensional_list=[[1,2,3],[4,5,6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is : ",two_dimensional_arr)

3D array creation:

import numpy as np
three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]]
three_dimensional_arr = np.array(three_dimensional_list)
print("3D array is : ",three_dimensional_arr)

ND array creation: This can be achieved by giving the ndmin attribute. The
below example demonstrates the creation of a 6D array:

import numpy as np
ndArray = np.array([1, 2, 3, 4], ndmin=6)
print(ndArray)
print('Dimensions of array:', ndArray.ndim)

63. You are given a numpy array and a new column as inputs.
How will you delete the second column and replace the
column with a new column value?
Example:
Given array:

[[35 53 63]
[72 12 22]
[43 84 56]]

Page 54 © Copyright by Interviewbit


Python Interview Questions

New Column values:

[
20
30
40
]

Solution:

import numpy as np
#inputs
inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]])
new_col = np.array([[20,30,40]])
# delete 2nd column
arr = np.delete(inputArray , 1, axis = 1)
#insert new_col to array
arr = np.insert(arr , 1, new_col, axis = 1)
print (arr)

64. How will you efficiently load data from a text file?
We can use the method numpy.loadtxt() which can automatically read the file’s
header and footer lines and the comments if any.
This method is highly efficient and even if this method feels less efficient, then the
data should be represented in a more efficient format such as CSV etc. Various
alternatives can be considered depending on the version of NumPy used.
Following are the file formats that are supported:

Page 55 © Copyright by Interviewbit


Python Interview Questions

Text files: These files are generally very slow, huge but portable and are human-
readable.
Raw binary: This file does not have any metadata and is not portable. But they
are fast.
Pickle: These are borderline slow and portable but depends on the NumPy
versions.
HDF5: This is known as the High-Powered Kitchen Sink format which supports
both PyTables and h5py format.
.npy: This is NumPy's native binary data format which is extremely simple,
efficient and portable.

65. How will you read CSV data into an array in NumPy?
This can be achieved by using the genfromtxt() method by setting the delimiter as a
comma.

from numpy import genfromtxt


csv_data = genfromtxt('sample_file.csv', delimiter=',')

66. How will you sort the array based on the Nth column?
For example, consider an array arr.

arr = np.array([[8, 3, 2],


[3, 6, 5],
[6, 1, 4]])

Let us try to sort the rows by the 2nd column so that we get:

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

We can do this by using the sort() method in numpy as:

Page 56 © Copyright by Interviewbit


Python Interview Questions

import numpy as np
arr = np.array([[8, 3, 2],
[3, 6, 5],
[6, 1, 4]])
#sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
order=['f1'],
axis=0).view(np.int)

We can also perform sorting and that too inplace sorting by doing:

arr.view('i8,i8,i8').sort(order=['f1'], axis=0)

67. How will you find the nearest value in a given numpy array?
We can use the argmin() method of numpy as shown below:

import numpy as np
def find_nearest_value(arr, value):
arr = np.asarray(arr)
idx = (np.abs(arr - value)).argmin()
return arr[idx]
#Driver code
arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value)) # Prints 0.5645

68. How will you reverse the numpy array using one line of
code?
This can be done as shown in the following:

reversed_array = arr[::-1]

where arr = original given array, reverse_array is the resultant a er reversing all
elements in the input.

69. How will you find the shape of any given NumPy array?

Page 57 © Copyright by Interviewbit


Python Interview Questions

We can use the shape attribute of the numpy array to find the shape. It returns the
shape of the array in terms of row count and column count of the array.

import numpy as np
arr_two_dim = np.array([("x1","x2", "x3","x4"),
("x5","x6", "x7","x8" )])
arr_one_dim = np.array([3,2,4,5,6])
# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)
"""
Output:
2-D Array Shape: (2, 4)
1-D Array Shape: (5,)
"""

Python Libraries Interview Questions


70. Differentiate between a package and a module in python.
The module is a single python file. A module can import other modules (other python
files) as objects. Whereas, a package is the folder/directory where different sub-
packages and the modules reside.
A python module is created by saving a file with the extension of .py . This file will
have classes and functions that are reusable in the code as well as across modules.
A python package is created by following the below steps:
Create a directory and give a valid name that represents its operation.
Place modules of one kind in this directory.
Create __init__.py file in this directory. This lets python know the directory
we created is a package. The contents of this package can be imported across
different modules in other packages to reuse the functionality.

71. What are some of the most commonly used built-in modules
in Python?
Python modules are the files having python code which can be functions, variables or
classes. These go by .py extension. The most commonly available built-in modules
are:

Page 58 © Copyright by Interviewbit


Python Interview Questions

os
math
sys
random
re
datetime
JSON

72. What are lambda functions?


Lambda functions are generally inline, anonymous functions represented by a single
expression. They are used for creating function objects during runtime. They can
accept any number of parameters. They are usually used where functions are
required only for a short period. They can be used as:

mul_func = lambda x,y : x*y


print(mul_func(6, 4))
# Output: 24

73. How can you generate random numbers?


Python provides a module called random using which we can generate random
numbers.
We have to import a random module and call the random() method as shown
below:
The random() method generates float values lying between 0 and 1
randomly.

import random
print(random.random())

To generate customised random numbers between specified ranges, we can use


the randrange() method
Syntax: randrange(beginning, end, step)
For example:

Page 59 © Copyright by Interviewbit


Python Interview Questions

import random
print(random.randrange(5,100,2))

74. Can you easily check if all characters in the given string is
alphanumeric?
This can be easily done by making use of the isalnum() method that returns true in
case the string has only alphanumeric characters.
For Example -

"abdc1321".isalnum() #Output: True


"xyz@123$".isalnum() #Output: False

Another way is to use match() method from the re (regex) module as shown:

import re
print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False

75. What are the differences between pickling and unpickling?


Pickling is the conversion of python objects to binary form. Whereas, unpickling is the
conversion of binary form data to python objects. The pickled objects are used for
storing in disks or external memory locations. Unpickled objects are used for getting
the data back as python objects upon which processing can be done in python.
Python provides a pickle module for achieving this. Pickling uses the
pickle.dump() method to dump python objects into disks. Unpickling uses the
pickle.load() method to get back the data as python objects.

Page 60 © Copyright by Interviewbit


Python Interview Questions

76. Define GIL.


GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to
python objects and aids in effective thread synchronization by avoiding deadlocks.
GIL helps in achieving multitasking (and not parallel computing). The following
diagram represents how GIL works.

Page 61 © Copyright by Interviewbit


Python Interview Questions

Based on the above diagram, there are three threads. First Thread acquires the GIL
first and starts the I/O execution. When the I/O operations are done, thread 1 releases
the acquired GIL which is then taken up by the second thread. The process repeats
and the GIL are used by different threads alternatively until the threads have
completed their execution. The threads not having the GIL lock goes into the waiting
state and resumes execution only when it acquires the lock.

77. Define PYTHONPATH.


It is an environment variable used for incorporating additional directories during the
import of a module or a package. PYTHONPATH is used for checking if the imported
packages or modules are available in the existing directories. Not just that, the
interpreter uses this environment variable to identify which module needs to be
loaded.

78. Define PIP.


PIP stands for Python Installer Package. As the name indicates, it is used for installing
different python modules. It is a command-line tool providing a seamless interface
for installing different python modules. It searches over the internet for the package
and installs them into the working directory without the need for any interaction
with the user. The syntax for this is:

pip install <package_name>

79. Are there any tools for identifying bugs and performing
static analysis in python?
Yes, there are tools like PyChecker and Pylint which are used as static analysis and
linting tools respectively. PyChecker helps find bugs in python source code files and
raises alerts for code issues and their complexity. Pylint checks for the module’s
coding standards and supports different plugins to enable custom features to meet
this requirement.

80. Differentiate between deep and shallow copies.

Page 62 © Copyright by Interviewbit


Python Interview Questions

Shallow copy does the task of creating new objects storing references of original
elements. This does not undergo recursion to create copies of nested objects. It
just copies the reference details of nested objects.
Deep copy creates an independent and new copy of an object and even copies
all the nested objects of the original element recursively.

81. What is main function in python? How do you invoke it?


In the world of programming languages, the main is considered as an entry point of
execution for a program. But in python, it is known that the interpreter serially
interprets the file line-by-line. This means that python does not provide main()
function explicitly. But this doesn't mean that we cannot simulate the execution of
main. This can be done by defining user-defined main() function and by using the
__name__ property of python file. This __name__ variable is a special built-in
variable that points to the name of the current module. This can be done as shown
below:

def main():
print("Hi Interviewbit!")
if __name__=="__main__":
main()

Python Programming Examples


82. Write python function which takes a variable number of
arguments.
A function that takes variable arguments is called a function prototype. Syntax:

def function_name(*arg_list)

For example:

Page 63 © Copyright by Interviewbit


Python Interview Questions

def func(*var):
for i in var:
print(i)
func(1)
func(20,1,6)

The * in the function argument represents variable arguments in the function.

83. WAP (Write a program) which takes a sequence of numbers


and check if all numbers are unique.
You can do this by converting the list to set by using set() method and comparing the
length of this set with the length of the original list. If found equal, return True.

def check_distinct(data_list):
if len(data_list) == len(set(data_list)):
return True
else:
return False;
print(check_distinct([1,6,5,8])) #Prints True
print(check_distinct([2,2,5,5,7,8])) #Prints False

84. Write a program for counting the number of every character


of a given text file.
The idea is to use collections and pprint module as shown below:

import collections
import pprint
with open("sample_file.txt", 'r') as data:
count_data = collections.Counter(data.read().upper())
count_value = pprint.pformat(count_data)
print(count_value)

85. Write a program to check and return the pairs of a given


array A whose sum value is equal to a target value N.

Page 64 © Copyright by Interviewbit


Python Interview Questions

This can be done easily by using the phenomenon of hashing. We can use a hash map
to check for the current value of the array, x. If the map has the value of (N-x), then
there is our pair.

def print_pairs(arr, N):


# hash set
hash_set = set()

for i in range(0, len(arr)):


val = N-arr[i]
if (val in hash_set): #check if N-x is there in set, print the pair
print("Pairs " + str(arr[i]) + ", " + str(val))
hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 3
print_pairs(arr, N)

86. Write a Program to add two integers >0 without using the
plus operator.
We can use bitwise operators to achieve this.

def add_nums(num1, num2):


while num2 != 0:
data = num1 & num2
num1 = num1 ^ num2
num2 = data << 1
return num1
print(add_nums(2, 10))

87. Write a Program to solve the given equation assuming that


a,b,c,m,n,o are constants:

ax + by = c
mx + ny = o

By solving the equation, we get:

Page 65 © Copyright by Interviewbit


Python Interview Questions

a, b, c, m, n, o = 5, 9, 4, 7, 9, 4
temp = a*n - b*m
if n != 0:
x = (c*n - b*o) / temp
y = (a*o - m*c) / temp
print(str(x), str(y))

88. Write a Program to match a string that has the letter ‘a’
followed by 4 to 8 'b’s.
We can use the re module of python to perform regex pattern comparison here.

import re
def match_text(txt_data):
pattern = 'ab{4,8}'
if re.search(pattern, txt_data): #search for pattern in txt_data
return 'Match found'
else:
return('Match not found')
print(match_text("abc")) #prints Match not found
print(match_text("aabbbbbc")) #prints Match found

89. Write a Program to convert date from yyyy-mm-dd format


to dd-mm-yyyy format.
We can again use the re module to convert the date string as shown below:

import re
def transform_date_format(date):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date)
date_input = "2021-08-01"
print(transform_date_format(date_input))

You can also use the datetime module as shown below:

from datetime import datetime


new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y")
print(new_data)

Page 66 © Copyright by Interviewbit


Python Interview Questions

90. Write a Program to combine two different dictionaries.


While combining, if you find the same keys, you can add the
values of these same keys. Output the new dictionary
We can use the Counter method from the collections module

from collections import Counter


d1 = {'key1': 50, 'key2': 100, 'key3':200}
d2 = {'key1': 200, 'key2': 100, 'key4':300}
new_dict = Counter(d1) + Counter(d2)
print(new_dict)

91. How will you access the dataset of a publicly shared


spreadsheet in CSV format stored in Google Drive?
We can use the StringIO module from the io module to read from the Google Drive
link and then we can use the pandas library using the obtained data source.

from io import StringIO


import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())

Conclusion:

Page 67 © Copyright by Interviewbit


Page 1

1.What is Python?
Answer:

ECH
It is powerful, general purpose, high level, object oriented programming language.
It’s developed by Guido Van Rossum in 1991..

2. Why we use Python?


Answer:
It is very simple and easy to learn.
It powerful, fast and secure.
It has very simple syntax.
It is powerful scripting language.
It can be run on different kind of platform like Windows , Mac, Linux, etc.,

3.What are the applications developed using Python?


Answer:
Web Application
Software Development
Database GUI application
Scientific and Numeric Computing
SYST
Business Applications
Console Based Application

4.What are the features in Python?


Answer:
Independent Platform
Object oriented
Flexible
Structure oriented
Portable
Simple

5.Is python, case sensitive language or not?


Answer:
Yes, python is a case sensitive language

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 2

6.Why indentation is required in Python?


Answer:

ECH
Indentation is necessary for Python. It specifies a block of code. All code within loops,
classes, functions, etc. And also it is specified within the indented block. It is usually done
by using four space characters. If your code is not indented necessarily, it will not execute
accurately and will throw errors as well.

7.What is an iterator in Python?


Answer:

An iterator is an object which implements the iterator protocol.


It has a __next__() method which returns the next item in iteration, also iterators are
objects which can iterate objects like list, string, etc.

8.Why python is called an interpreted language?


Answer:
An interpreted language is any programming language which is not in machine level
code before run time. Therefore, python is an interpreted language.
SYST
9.What is comment?
Answer:
Python comments are statements that are not executed by the compiler.
It is not considered as a part of program.
.

10.What are the types of comments in Python?


Answer:
There are two types of comment in Python.
Single line comment
Multi line comment

11.What is single line comment?


Answer:
It is used to comment only one line.
Hash (#) is used for single line comment.

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 3

12.What is multiline comment?


Answer:

ECH
It is used to comment a block of code.
Triple quotes are used to multiline comment starts with ‘’’ and ends with ‘’’.

13.What is Keyword?
Answer:
The word which is predefined in the library is called keyword.
Keywords cannot use as a variable function name, class name or any other identifier.

14.What is Float function?


Answer:
Float () is a predefined function which is used to convert given data into float.

15.What is int() function?


Answer:
int() is a predefined function which is used to convert string into integer.
SYST
16.What is print in Python?
Answer:
It is a predefined function which is used to print data or information..

17.How can you convert a number to a string?


Answer:
In order to convert a number into a string, use the inbuilt function str(). If you want a
octal or hexadecimal representation, use the inbuilt function oct() or hex().

18. What is Global variable?


Answer:
Variable are only referenced outside of that function known as global variable

19.What is an Operator?
Answer:
It is a special symbol which is used to perform logical or mathematical operation on
data or variable

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 4

20.What are the types of operator in Python?

ECH
Answer:
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Bit-wise operators
Membership operators
Identity operators

21. What is Operand?


Answer:
It is a data or variable on which the operation is to be performed

22. What is the use of // operator in Python?


Answer:
It is a Floor Division operator, which is used for dividing two operands with the result
as a quotient showing only digits before the decimal point. For instance, 10//5 = 2 and
10.0//5.0 = 2.0
SYST
23.What is the purpose of relational operators in Python?
Answer:
The purpose of relational operators in Python is to compare values.

24.What are assignment operators in Python?


Answer:
The assignment operators in Python can help in combining all the arithmetic operators
with the assignment symbol.

25.What are membership operators?


Answer:
With the operators ‘in’ and ‘not in’
print('me' in 'disappointment')
o/p: True

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 5

26.How to differentiate Identity operators & Membership operators?

ECH
Answer:
Unlike membership operators, the identity operators compare the values to find out if
they have the same value or not

27.What is import method?


Answer:
Import is a keyword, to access the script from another python file or module.

28.What is Input?
Answer:
Input () is a predefined function which is used to take user input in python.
Default user input is of type string

29.What is “if statement”?


Answer:
If the condition is true its body will execute otherwise does not execute

30.What is meant by for loop?


SYST
Answer:
For loop is used for sequential traversal.it can be used to traverse string or array. For
loop is used to iterate over a sequence list, string, tuple, etc., Iterating over a sequence
is called traversal.

31.How to print the star (*) pattern without newline and space?
Answer:
Code to print the star(*) pattern without newline and space:
for i in range(0, 20):
print('*', end="")

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 6

32.How will you create the following pattern using Python?


Answer:

ECH
*
**
***
****
o/p:
for i in range(1,6):
for j in range(1,i+1):
print('*',end='')
print(‘\n’)

33.What is list in Python?


Answer:
It is a collection of data of different data type.
It is used to store list of values.
A list is created by comma separated values between square brackets.

34. What is clear () function in list?


Answer:
SYST
This function is used to empty the list.

35.What are the built-in -type does python provides?

Answer:
Mutable:
List
Sets
Dictionaries
Immutable:
Strings
Tuples
Numbers

36.How can you count duplicate elements in a given list?


Answer:
Count duplicate elements in a given list
list1 = [2, 3, 4, 3, 10, 3, 5, 6, 3]
e = list1.count(3)
print('The count of element: 3 is ', e)

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 7

37.What is meant by continue statement?

ECH
Answer:
It is used to skip the next statement and continue the loop. This mostly used with loop.

38.What is copy () function in list?


Answer:
This function copies the elements one list into another.

39.What is count function in list?


Answer:
This method counts the number of occurrence of particular item in a list.

40.What is docstring in Python?


Answer:
Documentation string or docstring is a multiline string used to document a specific
code segment.
The docstring should describe what the function or method does.

41.What is meant by extend in list?


SYST
Answer:
This function is used to join two lists

42.What is append() function in list?


Answer:
It is used add the new element at the end of the list.

43.What is break statement?


Answer:
It terminates the current loop. Mostly used in for and while loop.

44.What is negative index in python?


Answer:
Python sequence can be index in positive and negative numbers.
For positive index, starts with 0 an soon. And negative index starts with (-1) in the last
index.

45.What is meant by Pass Python?


Answer:
Pass means no operation python statement

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 8

46.What is reverse function in list?


Answer:

ECH
This function reverses elements of the list

47.What is pop () function in list?


Answer:
This function deletes the element of given index.it deletes last item if we do not pass
index.

48.What is insert () function in list?


Answer:
Insert function is used to add new items into list at particular index.

49.What is meant by jump statement?


Answer:
It is used to transfer the control from one point to another point in the program.

50.What is sort function in list?


Answer:
This function sorts the list in ascending order or descending order.
SYST
51.What does len() do?
Answer:
It is used to determine the length of a string, a list, an array, etc.

Example:
S="ABCD"
print(len(S))

52. What is meant by Tuple?


Answer:
It is a collection of data of different data types.
We cannot change the value of tuples.
A tuple is created using parentheses.

53.Explain the output of the following piece of code?


Answer:
tuple=(123,'mani',20,'trichy')
tuple*=2
print(tuple)
o/p: (123, 'mani', 20, 'trichy', 123, 'mani', 20, 'trichy')
stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 9

54. What does the following code give us?


Answer:

ECH
b=(1)
print(type(b))
b=(1,)
print(type(b))

55.What is difference between python Arrays and Lists?


Answer:

Arrays:
Arrays in python can only contain same data type of elements.
Homogeneous
Consumes far less memory that lists
Lists:
List in python can contain elements of different data types.
Heterogeneous
Consuming large memory

56.What will the following code output?


SYST
Answer:
word=’abcdefghij’
word[:3]+word[3:]
The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.

57.What is the difference between List and Tuple?


Answer:
The difference between list and tuple is that list is mutable while tuple is not. Tuple can
be hashed,
For example, as a key for dictionaries

58.Describe about Slicing?


Answer:
A mechanism to select a range of items from sequence types like list, tuple, strings etc.,
is known as slicing.

59.What are sets in python?


Answer:
It is an unordered collection of data of different data types.
Set does not contain duplicate elements. A set is created using curly brackets

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 10

60.What is string in python?


Answer:

ECH
String is a collection of characters.it is created by using single quotes or double quotes.

61. How will you capitalize the first letter of string?


Answer:
In Python, capitalize () method capitalizes the first letter of a string. If the string
already consists of a capital letter at the beginning, then, it returns the original string..

62. How will you convert a string to all lowercase


Answer:
To convert a string to lowercase, lower() function can be used.
S="ABCD"
print(S.lower())

63.What if you want to toggle case for a Python string?


Answer:
print('SystECh'.swapcase())

o/p:
sYSTecH
SYST
64.How does break, continue and pass works in python?
Answer:

Allows loop termination when some condition is met and the control is
Break
transferred to the next statement.

Allows skipping some part of a loop when some specific condition is


Continue
met and the control is transferred to the beginning of the loop

Used when you need some block of code syntactically, but you want
Pass to skip its execution. This is basically a null operation. Nothing
happens when this is executed.

65.What is function in python?


Answer:
It is a collection of statement that performs on a specific task.
It executes when it is called by its name
stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 11

66.What is function overriding?

ECH
Answer:
Function with same name and same parameters is called function overriding.

67.What is the split function used for?


Answer:
The split function breaks the string into shorter strings using the defined separator.
It returns the list of all the words present in the string.

68.What is meant by Parameters and Arguments?


Answer:
Parameters are the names listed in the function definition.
Arguments are the values passed to the function while invoking.

69.What are packing operators in Python? How to use them?


Answer:
The packing operators are used to collect multiple arguments in functions.
They are known as arbitrary arguments.
SYST
70.What is Local variable?
Answer:
If a variable is assigned anywhere within the function’s body its assumed to be local.

71.What are python libraries?


Answer:
Python libraries are a collection of python packages.

Some of majorly used python libraries are;


NumPy
Pandas
Matplotlib
scikit-learn,
PyTorch and many more.

72.What are modules in python?


Answer:
A module is a collection of statement in which we store functions, classes and
variables.

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 12

73.What are some of the most commonly used built-in modules in Python?

ECH
Answer:
Python modules are the files having python code which can be functions, variables or
classes. These go by .py extension.
The most commonly available built-in modules are:

Os
Random
Datetime
Sys
Math

74.What is a lambda function?


Answer:
A lambda is an anonymous function. This function can have any number of
parameters but, can have just one statement.

Example: X=lambda a,b:a8b


Print(X(2,4))
SYST
75.Does Python have Oops concepts?
Answer:
Python is an object-oriented programming language .This means that any program can
be solved in python by creating an object model. However, python can be treated as
well as structural language.

76.What is class in Python?


Answer:
It is a collection of data members and member’s functions.
Data members are the variable used inside class
Member functions are the function used inside class
It is also called user defined data type

77.What is Parent class?


Answer:
The class which is inherited by another class is called parent or base class.

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 13

78.What is Child class?


Answer:

ECH
The class which inherits the property of another class is called child or sub or derived
class.

79.What is self in python?


Answer:
Self is an instance or an object of a class .it helps to differentiate between the methods
and attributes of a class with local variables.

80.Does python support multiple inheritances?


Answer:
Multiple inheritances mean that a class can be derived from more than one parent
classes. Python does support multiple inheritances.

81.What are the class variables in python?


Answer:
Private variable
Public variable
Protected variable
SYST
82.What is inheritance?
Answer:
The process of getting property of one class into another class is called inheritance

83.What is __init__ in python?


Answer:
__init__ is a method or constructor in python. This method is automatically called to
allocate memory when a new object is created. All classes have the __init__ method.

84.What is operator overloading?


Answer:
Operator overloading in python is a single operation based on the class (type) of
operands. Python operators work for built –in classes, the same operator behaves
differently with different types.

85..What is Encapsulation in python?


Answer:
Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP). It describes the idea of covering data and the methods that work on data within
one unit.
stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page 14

86.What is polymorphism in python?


Answer:

ECH
Polymorphism means the ability to take multiple forms. So, for instance, if the parent
class has a method named ABC then the child class also has a method with the same
name ABC having its own parameters and variables. Python allows polymorphism.

87.What is Data Abstraction?


Answer:
Abstraction means data hiding
If we want to perform data hiding then it can be done by using (__) prefix with variables
then they cannot be accessed outside that function

88.What is file handling in python?


Answer:
File handling is a mechanism to store the data on the disk permanently.
There are several functions for creating reading, writing, updating and deleting files.

89.What is file operation in python?


Answer:
1. Opening of file.
2. Writing into a file
SYST
3. Appending data into a file.
4. Reading from a file.
5. Closing of file.

90.What is read () function in file handling?


Answer:
read () function is used read content of a file.

91.How do you open a file for writing?


Answer:
_file=open('filename.txt','w')

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

file.close()

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page15

92.Give example of sleep() function in Python


Answer:

ECH
Example of sleep() function in Python

Import time
print("Welcome to SYSTECH GROUP")
time.sleep(5)
print("This message will be printed after a wait of 5 seconds")

93.What are Reasons of Exception?


Answer:
Mismatched input:

Suppose that we are entering our name in place of age, causing exception because age
is data type int and name will be string.
Defined Data type:

Class keyword is used to create class

94.What is try block?


Answer:
SYST
It is the place where actual code is written and exception occurs.

95.What is except block?


Answer:
Except block is intended to catch the error and handle the exception condition. We can
have multiline except blocks to handle different types of exception and perform
different actions when the exceptions occur.

96.What is finally block?


Answer:
This block executes either exception occurs or does not occurs.

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page16

97. Explain important Python errors?


Answer:

ECH
The important Python errors are
1) Arithmetic Error, 2) Import Error, and 3) Index Error.

Arithmetic Error:
Arithmetic Error acts as a, base class for all arithmetic exceptions. It is raised for errors
in arithmetic operations.

Import Error:
Import Error is raised when you are trying to import a module which does not present.
This kind of exception occurs if you have made a typing mistake in the module name or
the module which is not present in the standard path.

Index Error:
An Index Error is raised when you try to refer a sequence which is out of range.

98.What is the output of the following code?


Answer:
SYST
first = [1, 2, 3, 4, 5]
second = first
second.append(6)
print(first)
print(second)
o/p:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

99.How a file is deleted in Python?


Answer:
The file can be deleted by either of these commands:
os.remove(filename)
os.unlink(filename)

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Page17

100.What is difference between python and other programming languages?

Answer:

. C C++ PYTHON

Longer lines of code as 3-5 times shorter than


Longer lines of code as
compared to python. C/C++ programs.
compared to python.

Longer lines of code as Python has no


Longer lines of code as
compared to python. declaration.
compared to python.

C is a compiled C++ is a compiled Python is an


language. language. interpreted language.

Python supports
C++ supports both procedural, object-
C supports procedural procedural and object oriented, and
programming. oriented programming. functional
programming.

C++ support both single


Python supports5 types
C supports procedural and multiple
of inheritance
programming. inheritance

stechgroup.in
sy
roup contact@
systechg 7502202555
www.systechgroup.in
Python Interview Questions for Freshers

1. What is Python?
Python is a general-purpose computer programming language based on object-oriented
programming. The programs in Python can run equally on every operating system. It is the
primary language used in modern technologies like AI, data science, and ML.

2. Python was developed in which year?


It was developed in 1991.

3. What are the primary uses of Python?


Here is the list of some areas where Python programming language is used:
● Data Analysis
● Software testing
● Web development
● Software and application development
● Game development
● Automation and scripting
● Machine Learning
● Artificial Intelligence
● Data science and data visualization
● Desktop GUI
● Blockchain
● Image processing and graphic applications
● Creating operating systems
● Prototyping
● Everyday tasks like downloading audio and video files, updating the lists, converting
files, filling information, renaming and arranging large batches, setting notifications,
and many more.

4. Who uses Python?


Most of the big names in the industry are using Python language for their operations. Brands
like IBM, NASA, Pixer, Facebook, Spotify, Intel, YouTube, Instagram, Pinterest, Reddit, etc.,
use Python as one of the primary languages.

5. What are the benefits of using Python?


Python has various benefits, and some of them are:

● Easy to read and write


● Interpreted language
● Vast library functions
● Portable across various operating systems
● Efficiency
● Presence of third party modules
● Various data analysis tools.
● Object-oriented programming base
● Open-source library
● Rich frameworks
● Testing instruments

6. How to write a program in Python?


Before writing a program in Python, there should be an interpreter like PyCharm installed on
the system.

● Create a new project


● Select a location or storage space where files will be stored
● Click on the create button and select the new file
● Name the file
● Type a simple program
● Run the program from the run option in the Menu
● The output will be at the bottom of the screen

7. Where to run Python code?


You can run a Python code from the run option in the menu in an interpreter. A Python code
can also run in command prompt code. It will run the program after entering the correct path
of the file.

8. What is a function in Python with example?


A function in Python is a code block that runs when it is called in a program. Data can be
passed into the function with the help of this, and it is known as a parameter. The function
can also return data as results.

9. How many functions are there in Python?


There are basically three types of functions in Python:

● Built-in functions: These functions come defined with the Python language. Here
are some of the built-in functions in Python:
➔ print() function
➔ len() function
➔ sum() function
➔ sorted() function
➔ dir() function
➔ max() function

● User-defined functions: These functions are defined by the user to perform a task
in the program. These are defined with the def keyword at the start. These functions
are written like this:
➔ def add_numbers()
➔ def entry()
● Anonymous functions: These are the functions that are defined without a name.
These are also called lambda functions. These are used when a user needs a
function for a little time in function. It is written as— lambda()

10. Where is a Python function defined?


A function in Python is called with the help of the def keyword. A function block starts with
this keyword, and then function name and parentheses(()) take place. Arguments are placed
between this, and parameters can also be defined inside of this.

11. Is Python code compiled or interpreted?


Python code is interpreted. A Python code is converted into bytecode that is executed by a
virtual machine in Python. A Python program is not needed to build like code for other
languages where it is compiled, and it works on an interpreter only.

12. What is a dynamically typed language?


Type checking takes place at execution in a dynamically typed language. The variables are
checked against types only when the code is executing. Programming languages like
Python, JavaScript, PHP, Lisp, etc., come under this type.

The exact same variable can be used multiple times in a program in a dynamically typed
language like Python.

13. What are Python literals?


The raw data that is assigned to constants and variables are defined as literals in Python.
Basically, these are used to represent a fixed value in the source code. It can be either a
string type, a numeric type, a boolean type, etc.

14. What is an Interpreted language?


When the implementation of the programs is done directly without compilation of the
program into machine language, the language is called interpreted language. These
languages are slower than the compiled languages.

All the debugging occurs at run time in this language. Python, JavaScript, Perl, etc., are
some of the examples of interpreted languages.

15. What is Python virtualenv?


The isolated environment for development and debugging Python is called virtualenv. It runs
multiple applications with the help of pip. It is also used to isolate a Python interpreter with
settings and libraries.

It is a tool that is used for storing copies of Python and pip that are installed from the
projects. With the help of this, a user can work on multiple projects on the same machine at
the exact same time.

16. What do you think of the future of Python?


Most future technologies are mostly dependent on Python, and that is what makes it one of
the most used languages.

Python is very popular, and it is used as it is less complex than other languages. The future
is of Artificial Intelligence (AI) and Machine Learning (ML). Because the majority of
programming in ML and AI is done with Python, the future of the language contains more
opportunities.

17. How to reverse a list in Python?


The function that is used to reverse a list in Python is list.reserve()

18. What is the role of map() function in Python?


The Python map() function processes and transforms the iterable like tuples and lists without
using for loop.

19. What is a Try block in Python?


It is a block that is preceded with the help of the try keyword.

20. What is the shortest method to open a text file and display
content?
Using the ‘with’ command is the shortest way to open a text file and display the content in it.

21. Can you write a Python program to add two integers that
are greater than zero without using the plus operator?
Yes, I can do it with the help of a bitwise operator.

22. What will be the output of this program?


A[2]=[1,3,4,5,8,9,11,56]
The indexing starts from zero, and the element at the second index is 4. The output will be 4.

23. What is the Python dictionary?


A dictionary in Python is a collection of items that are written in curly brackets with keys and
values. The items are in no particular order and are used to retrieve the value for keys that
are known.

24. Differentiate between new and override modifiers in


Python.
If there are two methods with the exact same name to perform different tasks and provide
different functionality, the concept of overriding is used.

The new modifiers hide the original method, which provides different functionality. The
original method can also be accessed by the base class.

25. What is pass in Python?


Pass is a statement in Python that is used as a placeholder for upcoming codes. At
execution, it does not show any error, but it is not allowed in loops, class definitions, if
statements, or function definitions.

Basically, it is a null statement, and when it is executed, it will result in no operation.

26. What is recursion in Python?


When the functions call themselves in a program, the process is known as recursion. It has
two parts, the base case and the recursive case.

The base case is used to stop the recursion, and the recursive base is where the function
calls itself.

27. What are the basic applications of Python?


The basic applications of Python include:

● Web and web framework applications


● Image processing applications
● GUI based desktop applications
● Prototyping
● Game development
● Data processing

28. Tell me the names of some Python built-in modules?


● OS module
● Random module
● Sys module
● JSON
● Math module
● Collective module

29. How does closure occur in Python?


When a nested function defines a value in an enclosing scope, the closure occurs in the
program. It remembers the values.

30. Tell me something about SciPy.


All the numerical code is stored in SciPy. It contains a better version of the linear algebra
modules with more features. There are more algebra modules in SciPy as well.
31. What is the enumerate() function in Python?
Enumerate() is a function that is used to iterate through a sequence. It keeps track of both
elements and the index. It takes the collection and returns it as an enumerated object.

32. How does Python do Compile-time and Run-time code


checking?
Python does not perform compile-time code checking except when the code is syntactically
invalid. If the code is following the syntax rules, it will compile without even checking it.

Python run time code checking is done dynamically. All the parts of the program are checked
at runtime.

33. What are the common built-in data types in Python?


- Binary type
- Boolean type
- Set type
- Mapping type
- Sequence type
- Numeric types
- Text type

34. What is the basic difference between .py and .pyc files?
.py files have the source code of a program, while the .pyc files have the bytecode of a
Python program. Python compiles the .py files and saves them as .pyc files.

35. What are comments in Python? What are different types of


comments?
Comments are text with the information in Python. These are used when two or more
programmers are working on a project. The use of Python comments is to analyze, debug,
and provide feedback.

Comments are of two types:

● Single line comment


● Multiple line comment
36. What are global, private, and protected attributes in
Python?
- Global variables are defined in the global scope. Global keyword is used for using it
in global scope in a function.
- Private attributes have double underscores as prefixes to their identifiers. They can
not be accessed from outside directly, which results in AttributeError.
- Protected attributes have an underscore as a prefix to their prefix. It can also be
accessed from outside the class.

37. How to remove duplicate elements from a list in Python?


Duplicate elements can be removed from the list by turning them into the set. The set (list)
function is used for it.

38. What is Python Tkinter?


Tkinter in Python is a library and toolkit for GUI development. It has attributes like
dimensions, fonts, colors, etc. It also gives support for various GUI applications.

39. What is Pyramid in Python?


A Python pyramid is made for larger applications. We can select a database, URL structure,
templating style, database, etc., with the help of a pyramid. It provides flexibility as it is a
heavy configuration program.

40. Is tuple comprehension possible in Python?


No, it is not possible because it will end up in a generator instead of a tuple comprehension.

41. What is the work of # in Python?


It is used to comment out everything that comes after on the line in Python.

42. What is the minimum and maximum length of an identifier


in Python?
Identifiers can be of any length. There are no limitations on length in Python.

43. What are modules and packages in Python?


A package holds sub-packages and modules, and the file __init__.py is used in the package
for holding user-interpreted codes.

A module is a file that has Python code. It also modifies the code to get executed in run time.
It consists of the unit namespace, which also has extracted variables.

The modules prevent collision between global variable names, and packages do the same
between module names. The packages are also reusable, and that is why they are
preferred.

44. What is Scope in Python?


In Python, the location where we can find a variable and can access it when it is required is
called scope. This is of two types: global and local.

Global variables are the ones that can be used by any part of the program and can be
declared outside of any function.

Python Interview Questions for Experienced


Professionals

1. Which is the best Python code to Java code converter?


Jython is mostly used for using Python codes on the Java platform. It is an open-source
implementation of Python code integrated with Java.

The code is compiled to Java bytecode and runs on any Java virtual machine. It gives
access to all the Java libraries.

2. What are some Python code best practices?


Here are some of the best Python code practices that a developer should follow:
● Creating a code repository for Python and implementing version control
● Creating readable documentation
● Following style guidelines in Python
● Fixing broken codes instantly
● Using virtual environments
● Using Python package indexes
● Writing easy and readable codes
● Using the correct data structures
● Using codes that are object-oriented

3. In Python 3 and later, what is the use of a nonlocal statement?


It is used to assign values to a variable in an outer scope. It causes listed identifiers to refer
to the previous variable in the nearest enclosing scopes.

4. If you installed a module with the pip, but it doesn’t import in


your IDLE, what are the possible reasons?
There can be two possible issues in this process:
● If the system has Python 2. Since NumPy is installed for Python 3.6 and the latest
versions, this will show an error.
● Check if there is an issue with the configuration of the anaconda with IDLE. If the
system is using default Python in place of anaconda, NumPy can not be installed.

5. What is os.walk() function?


The os.walk() is a function that generates the file names in the directory tree. It is done by
walking the tree either bottom-up or top-down. It yields a 3-tuple for each directory, which are
dirpath, dirnames, and filenames.

6. How is staticmethod different from classmethod?


Both the methods are used to define a class method that is installed without instantiating the
object in a class. The signature in both methods is different.

7. .What is the use of the PYTHONSTARTUP environment


variable in the Python program?
The PYTHONSTARTUP environment variable is used to specify the particular location of the
path to a file in Python. It can also be used in setting colors and preloading modules. This
script will run before the interpreter.
.
8. What is the use of the PYTHONCASEOK environment variable
in the Python program?
It is used to find the first case-sensitive matches in the import statements. It is used to ignore
all import statements while calling the interpreter in Python.

9. What is PEP 8, and tell me about its importance?


PEP 8 is a document that guides the users with best practices on a Python program. The
document was written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001.

With the primary focus on improving the readability and consistency of Python code, Python
Enhancement Proposal or PEP is also used for improving the design and style of a program.

10. What are decorators in Python?


Decorators in Python are used to add functionality to a class or a function. It can change the
behaviour of a class without permanent modification in it.

11. What is the dogpile effect? What would you do to prevent


this effect?
When the cache expires, and the client requests multiple times for the website at the same
time, the dogpile effect occurs.

I will use the semaphore lock to prevent this effect. Because when the value expires, it will
acquire the lock and generate a new value.

12. What is multithreading in Python?


When several programs are running concurrently by invoking multiple threads, the process is
called multithreading. The Thread class in Python is a predefined class. It is defined in the
threading module.
It is a lightweight process. Several threads refer to the data space with the main thread and
share information easily by communicating with each other. Threads can be used for
calculating results while the main part of the program is running.

13. What is Python's parameter passing mechanism?


Parameter passing can be done by two methods in Python:
● Pass by reference: All the arguments are passed by reference in any function in
Python. When the value of the parameter is changed within the function, the change
can also be seen in the calling function.
● Pass by value: When an argument in the program is passed to the function, only
values pass to the function, leaving reference behind. It is not changeable and
immutable.

14. How good is Python for data analysis?


Python is very good for data analysis. Processes like data mining, data processing, and data
visualization are done easily with the help of Python.

15. Tell me about the use of frozenset in Python?


The frozenset is a collection of unique values in Python. It is an immutable collection that is
made of distinct hashable objects. The values in the frozenset can not be changed, and
methods from the set on the frozenset can’t be used and updated.

16. What are the differences between Python 2 and Python 3?


Python 2 is faster than Python 3. The print keyword is considered a statement in 2 and a
function in 3. Strings are stored as ASCII as default in version 2, while UNICODE is in
version 3 as default.

The xrange() function is used for iterations in Python 2, and the range() function is used to
perform iterations in Python 3. Version 2 is used by the DevOps engineer, and version 3 is
used in fields like data science and software engineering.

The syntax is also easier in Python 3 than in Python 2. Many libraries in Python 2 are not
forward compatible and are strictly used with Python 3.

When the division of integers is performed, version 2 of Python gives an integral value while
version 3 provides floating type values.

Exceptions are enclosed in notations in Python 2 and enclosed in parentheses in Python 3. If


variables are used in a for loop, the values change in Python 2 but never change in Python
3.

17. What is the execution time for else part of a try-except


block?
The else part of the try-except block will execute when there is no exception in the program.
18. Is it possible to call the parent class without its instance
creation?
Yes, it is possible by creating an object of the child class and calling the function of the
parent class in the Python program with the help of the dot operator.

19. What are Python namespaces? Why are they used?


A namespace in Python is a system that has a unique name for every object. It is used to
implement scope, and it is created when a function, package, or module is evaluated.
Basically, It is used to organize codes into logical groups when there are multiple libraries.

20. How will you combine data frames in pandas?


The data frames in pandas can be combined with three methods:
● Concatenating dataframes by stacking the two of them vertically.
● Concatenating dataframes by stacking the two of them horizontally.
● Combining dataframes on a common column is called joining.

21. How is OOPS used in Python?


OOPS is a paradigm in Python that uses classes and objects. Coding is done with the help
of real-world elements like class, data abstraction, polymorphism, inheritance,
encapsulation, etc.

22. What is encapsulation in Python?


It is a concept in OOP that is used to wrap data and the methods that work on data within a
single unit. This helps a Python program to restrict the variable that is used to prevent
unnecessary modifications and changes to the data.

With encapsulation, the data can be changed by the method of the object. These methods
are called private variables. A class is a good example of encapsulation in Python as it is
used to encapsulate the data like variables and member functions.

23. What is inheritance in Python?


It is the capability of one class in the program that is used to inherit the properties from
another class. The class that derives properties is called the child class or derived class, and
the class from which the properties are derived is known as the parent class or base class.

24. Tell me about the types of inheritance?


Inheritance is of four types:
● Single inheritance
● Multilevel inheritance
● Multiple inheritances
● Hierarchical inheritance

25. What are the advantages of using inheritance in Python?


Here are some of the key advantages of using inheritance in a Python code:
● It provides the reusability of the code.
● It is used for showing real-time relationships.
● It allows additional features to a class in the code without any modification.
● It is transitive in nature.

26. What is data abstraction in Python?


Data abstraction is used for hiding the actual implementation of the Python program, and it is
done by showing only the functionalities.

If a class has one abstract function, it is called an abstract class. Once the module is
imported from the ABC (Abstraction Base Class) module, abstract methods can be created
in a Python program.

27. What is polymorphism in Python?


It means to have multiple forms of any object in a Python program. A code can be used to
determine and differentiate the program.

Python Programs for Interview Preparation


1. Python code for printing HelloWorld

2. Python code to add two or more numbers

3. Python code to find factorial of a number

4. Python code to reverse a string

5. Python code for snake game

6. Python code for building a calculator

7. Python code for cracking a Wi-Fi password

8. Python code to check prime number

9. Python code for Fibonacci series

10. Python code for sending WhatsApp messages

You might also like