Python Interview Questions
Python Interview Questions
Frequently
Python
Asked
Interview
Questions
w i t h a n s w e r s
Basic Level
Shallow copy creates a different object and populates it with the references
of the child objects within the original object. Therefore, changes in the
original object are reflected in the copy.
Page no: 2
Get free mentorship
from experts?
4. What Advantage Does the Numpy Array Have over a Nested List?
Answer:
Numpy is written in C so that all its complexities are backed into a simple to use
a module. Lists, on the other hand, are dynamically typed. Therefore, Python
must check the data type of each element every time it uses it. This makes
Numpy arrays much faster than lists.
Numpy has a lot of additional functionality that list doesn’t offer; for instance, a
lot of things can be automated in Numpy.
Pickling Unpickling
of Aptitude and Technical skills C++, Java, Python, DSA, CN, OS, DBMS,
After knowing the current level it will Quant, Reasoning, and verbal ability.
become easy for a student to start their Topic-wise questions in every test will help
placement preparation students get strong and weak points
If you just created a neural network model, you can save that model to your hard
drive, pickle it, and then unpickle to bring it back into another software program
or to use it at a later time.
Answer:
Arguments are passed in python by a reference. This means that any changes
made within a function are reflected in the original object.
Consider two sets of code shown below:
Page no: 4
Join WhatsApp Group for
Placement
In the first example, we only assigned a value to one element of ‘l’, so the output
is [3, 2, 3, 4].
In the second example, we have created a whole new object for ‘l’. But, the
values [3, 2, 3, 4] doesn’t show up in the output as it is outside the definition of
the function.
Page no: 5
10. What Does the ‘is’ Operator Do? Get free mentorship
from experts?
Answer:
The ‘is’ operator compares the id of the two objects.
list1=[1,2,3]
list2=[1,2,3]
list3=list1
list1 == list2 🡪 True
list1 is list2 🡪 False
list1 is list3 🡪 True
Answer:
Python has an inbuilt method isalnum() which returns true if all characters
in the string are alphanumeric.
Example -
>> "abcd123".isalnum()
Output: True
>>”abcd@123#”.isalnum()
Output: False
Another way is to use regex as shown.
>>import re
>>bool(re.match(‘[A-Za-z0-9]+$','abcd123’))
Output: True
>> bool(re.match(‘[A-Za-z0-9]+$','abcd@123’))
Output: False
Page no: 6
Follow us on Instagram
Page no: 7
Join WhatsApp Group for
Placement
del remove()
Page no: 8
Get free mentorship
from experts?
17. How Do You Display the Contents of a Text File in Reverse Order?
Answer:
You can display the contents of a text file in reverse order using
the following steps:
· Open the file using the open() function
· Store the contents of the file into a list
· Reverse the contents of the list
· Run a for loop to iterate through the list
append() extend()
Output:
list1 = [1,’a’]
list2 = [123]
lilst3 = [1,’a’]
Page no: 10
Join WhatsApp Group for
Placement
Note that list1 and list3 are equal. When we passed the information to the
addToList, we did it without a second value. If we don't have an empty list as the
second value, it will start off with an empty list, which we then append. For list2,
we appended the value to an empty list, so its value becomes [123].
For list3, we're adding ‘a’ to the list. Because we didn't designate the list, it is a
shared value. It means the list doesn’t reset and we get its value as [1, ‘a’].
Remember that a default list is created only once during the function and not
during its call number.
Example -
def add(a,b):
" " "This function adds two numbers." " "
sum=a+b
return sum
sum=add(10,20)
print("Accessing doctstring method 1:",add.__doc__)
print("Accessing doctstring method 2:",end="")
help(add)
Page no: 11
Get free mentorship
from experts?
Output -
Accessing docstring method 1: This function adds two numbers.
Accessing docstring method 2: Help on function add-in module __main__:
add(a, b)
This function adds two numbers.
Place
d in A Rohit Borse
ccent
ure
Shrinija
Kalluri 6.5 LP
Placed in
Oracle A
9 LPA
Page no: 12
Follow us on Instagram
kwargs
It is used in a function prototype to accept the varying number of keyworded
arguments.
·It's an iterable object
·Usage - def fun(**kwargs):
fun(colour=”red”.units=2)
Answer:
It means that a function can be treated just like an object. You can assign them
to variables, or pass them as arguments to other functions. You can even return
them from other functions.
Page no: 13
Join WhatsApp Group for
Placement
Matrices Arrays
Page no: 14
Advanced Level
32. How Would You Obtain the Res_set from the Train_set and the
Test_set from Below?
>>train_set=np.array([1, 2, 3])
>>test_set=np.array([[0, 1, 2], [1, 2, 3])
Res_set 🡪 [[1, 2, 3], [0, 1, 2], [1, 2, 3]]
4.None of these
Answer:
Here, options a and b would both do horizontal stacking, but we want vertical
stacking. So, option c is the right statement.
resulting_set = np.vstack([train_set, test_set])
Answer:
3. from sklearn.tree import DecisionTreeClassifier
35. What Is the Difference Between the Two Data Series given Below?
Answer:
3. Both are copies of the original dataframe.
Page no: 16
Join WhatsApp Group for
Placement
36. You Get the Error “temp.Csv” While Trying to Read a File
Using Pandas. Which of the Following Could Correct It?
Error:
Traceback (most recent call last): File "<input>", line 1,
in<module> UnicodeEncodeError:
'ascii' codec can't encode character.
Answer:
The error relates to the difference between utf-8 coding and a Unicode.
So option 3. pd.read_csv(“temp.csv”, encoding=’utf-8′) can correct it.
37. How Do You Set a Line Width in the Plot given Below?
Page no: 17
Get free mentorship
from experts?
Answer:
3. In line two, write plt.plot([1,2,3,4], lw=3)
38. How Would You Reset the Index of a Dataframe to a given List?
Answer:
3. df.reindex_like(new_index,)
Answer:
The function used to copy objects in Python are:
copy.copy for shallow copy and
copy.deepcopy() for deep copy
Answer:
range() xrange()
41. How Can You Check Whether a Pandas Dataframe Is Empty or Not?
Answer:
42. If You Split Your Data into Train/Test Splits, Is It Possible to over
Fit Your Model?
Answer:
Yes. One common beginner mistake is re-tuning a model or training new
models with different parameters after seeing its performance on the test
set.
Page no: 19
Join WhatsApp Group for
Placement
Talent Battle is
associated with TCS iON
for content partnership &
providing internships to
students across India.
Page no: 20
Get free mentorship
from experts?
Page no: 21
Follow us on Instagram
Yield Except
For Del
Else Continue
Elif Class
If Assert
Not With
Or Try
And False
Raise True
·Nonlocal Return
None Pass
Is Lambda
In Def
Import As
Global Break
From While
Finally
Page no: 22
Join WhatsApp Group for
Placement
56. What are the key features of the Python 3.9.0.0 version?
Answer:
Zoneinfo and graphlib are two new modules.
Improved modules such as asyncio and ast.
Optimizations include improved idiom for assignment, signal handling, and
Python built-ins.
Removal of erroneous methods and functions.
Instead of LL1, a new parser is based on PEG.
Remove Prefixes and Suffixes with New String Methods.
Generics with type hinting in standard collections.
Answer:
Python's private heap space is in charge of memory management. A
private heap holds all Python objects and data structures. This
secret heap is not accessible to the programmer. Instead, the
Python interpreter takes care of it.
Python also includes a built-in garbage collector, which recycles all
unused memory and makes it available to the heap space.
Python's memory management is in charge of allocating heap
space for Python objects. The core API allows programmers access
to some programming tools.
Page no: 24
61. How to install Python on Windows and set path variables?
Answer:
Download Python from https://www.python.org/downloads/
Install it on your computer. Using your command prompt, look for
the location where PYTHON is installed on your computer by typing
cmd python.
Then, in advanced system settings, create a new variable called
PYTHON_NAME and paste the copied path into it.
Search the path variable, choose its value and select ‘edit’.
If the value doesn't have a semicolon at the end, add one, and then
type %PYTHON HOME%.
Follow us on Instagram
Page no: 25
Join WhatsApp Group for
Placement
JSON
data time
random
math
sys
OS
Page no: 26
69. What is the Lambda function? Get free mentorship
from experts?
Answer:
A lambda function is a type of anonymous function. This function can
take as many parameters as you want, but just one statement.
Answer:
Lambda is typically utilized in instances where an anonymous function
is required for a short period of time. Lambda functions can be applied
in two different ways:
Page no: 27
Follow us on Instagram
73. Differentiate between range and xrange.
Answer:
In terms of functionality, xrange and range are essentially the same.
They both provide you the option of generating a list of integers to
use whatever you want. The sole difference between range and
xrange is that range produces a Python list object whereas x range
returns an xrange object. This is especially true if you are working
with a machine that requires a lot of memory, such as a phone
because range will utilize as much memory as it can to generate
your array of numbers, which can cause a memory error and crash
your program. It is a beast with a memory problem.
Deep Copy: Deep Copy recursively replicates all values from source to
destination object, including the objects referenced by the source object.
from copy import copy, deepcopy
Page no: 28
Join WhatsApp Group for
Placement
80. What are negative indexes and why are they used?
Answer:
·The indexes from the end of the list, tuple, or string are called negative
indexes.
·Arr[-1] denotes the array's last element. Arr[]
Page no: 30
82. What method will you use to convert a string to all lowercase?
Answer:
The lower() function can be used to convert a string to lowercase.
85. What are the functions help() and dir() used for in Python?
Answer:
Both help() and dir() are available from the Python interpreter and are used to
provide a condensed list of built-in functions.
dir() function: The defined symbols are displayed using the dir() function.
help() function: The help() function displays the documentation string and also
allows you to access help for modules, keywords, attributes, and other items.
86. Why isn't all the memory de-allocated when Python exits?
Answer:
When Python quits, some Python modules, especially those with circular
references to other objects or objects referenced from global namespaces,
are not necessarily freed or deallocated.
Python would try to de-allocate/destroy all other objects on exit because it
has its own efficient cleanup mechanism.
It is difficult to de-allocate memory that has been reserved by the C library.
Follow us on Instagram
Page no: 31
Join WhatsApp Group for
87. What is a dictionary in Python? Placement
Answer:
Dictionary is one of Python's built-in datatypes. It establishes a one-to-one
correspondence between keys and values. Dictionary keys and values are
stored in pairs in dictionaries. Keys are used to index dictionaries.
94. What is the best way to remove values from a Python array?
Answer:
The pop() and remove() methods can be used to remove elements from an
array. The difference between these two functions is that one returns the
removed value while the other does not.
Page no: 33
Follow us on Instagram
Page no: 34
Join WhatsApp Group for
Placement
Page no: 36
A session is just a way of remembering information from one request to the
next. A session in a flask employs a signed cookie to allow the user to inspect
and edit the contents of the session. If the user only has the secret key, he or
she can change the session. Flask.secret key.
Flask is easier to use than Django, but it doesn't do much for you, so you will
have to specify the specifics, whereas Django does a lot for you and you won't
have to do anything. Django has prewritten code that the user must examine,
whereas Flask allows users to write their own code, making it easier to grasp.
Both are technically excellent and have their own set of advantages and
disadvantages.
Follow us on Instagram
Page no: 37
113. What is the use of sessions in the Django framework?
Answer:
Django has a session feature that allows you to store and retrieve data for each
site visitor. Django isolates the process of sending and receiving cookies by
keeping all necessary data on the server-side and inserting a session ID cookie
on the client-side.
The unary operator, which requires only one operand, the binary operator, which
requires two operands, and the ternary operator, which requires three operands.
97.6% 4.91 / 5
Selection Ratio Overall Rating
of Complete Masterclass Students out of 5
JOIN NOW
Our Team
Industry Mentors
@talentbattle.in
@talentbattle_2023
@talentbattle_2024
@talentbattle_2025
@talentbattle_2026
WhatsApp Group
Free Mentorship
Talent Battle Facebook
Talent Battle YouTube
Talent Battle LinkedIn
https://talentbattle.in/