150 Python Interview Q&A
150 Python Interview Q&A
Deepcopycreatesadifferentobjectandpopulatesitwiththechildobjectsoftheoriginalobject.Therefore,
copy.deepcopy()createsaDeepCopy.
Ashallowcopycreatesadifferentobjectandpopulatesitwiththereferencesofthechildobjectswithintheo
riginalobject.Therefore,changes intheoriginalobjectare reflectedinthecopy.
copy.copycreatesaShallowCopy.
Multithreadingusuallyimpliesthatmultiplethreadsareexecutedconcurrently.ThePythonGlobalInterpr
eter Lock doesn't allow more than one thread to hold the Python interpreter at thatparticular point
of time. So, multithreading in Python is achieved through context switching. It isquitedifferent
frommultiprocessing which opensup multiple processesacross multiplethreads.
HereyoucanalsofindacomprehensiveguideonPythonDjangoTutorialthatisveryeasyto
understand.
Django is a web service used to build your web pages. Its architecture is as shown:
• Template:thefrontendofthewebpage
• Model:thebackendwherethedataisstored
• View:ItinteractswiththemodelandtemplateandmapsittotheURL
• Django:servesthepagetotheuser
4. What Advantage Does the Numpy Array Have over
aNested List?
Numpy is written in C so that all its complexities are backed into a simple-to-use module. Lists,
onthe other hand, are dynamically typed. Therefore, Python must check the data type of
eachelement every time it uses it. This makes Numpy arrays much faster than lists.
Numpyhasalotofadditionalfunctionalitythatthelistdoesn’toffer;forinstance,alotofthingscanbe
automated in Numpy.
Pickling Unpickling
• ConvertingabytestreamtoaPythonobjecthier
• ConvertingaPythonobjecthierarchytoabyt archyiscalledunpickling
estreamiscalledpickling • Unpicklingisalsoreferredtoasde
• Picklingisalsoreferredtoasserialization serialization
If you just created a neural network model, you can save that model to your hard drive,
pickleit, and then unpickle it to bring it back into another software program or use it at a later
time.
The following are some of the most frequently asked Python interview questions
Python has a private heap space that stores all the objects. The Python memory
managerregulates various aspects of this heap, such as sharing, caching, segmentation,
andallocation. The user has no control over the heap; only the Python interpreter has
access.
7. AreArgumentsinPythonPassedbyValueorbyReference?
Arguments are passed in Python by a reference. This means that any changes made
withina function are reflected in the original object.
Consider two sets of code shown below:
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]don’t show up in the output as it is outside the definition of the function.
8. HowWouldYouGenerateRandomNumbersinPython?
TogeneraterandomnumbersinPython,youmustfirstimporttherandommodule.The
> random.random()
In Python, the / operator performs division and returns the quotient in the
The//operator,ontheotherhand,returnsthequotientinaninteger.For
example: 5 // 2 returns 2
10. What Does the ‘is’ Operator Do?
objects.list1 = [1,2,3]
list2 =
[1,2,3]list3 =
list1
list1==list2=>Truelis
t1 is list2 =>
Falselist1islist3=>Tr
ue
The pass statement is used when there's a syntactic but not an operational requirement.
Forexample - The program below prints a string ignoring the spaces.
var="Si mplilea
rn"for i in var:
if i==" ":
pass
else:
print(i,end="")
Here,thepassstatementrefersto‘noactionrequired.’
12. HowWillYouCheckIfAlltheCharactersinaStringAre
Alphanumeric?
Python has an inbuilt method isalnum() which returns true if all characters in the string
arealphanumeric.
Example -
>>
"abcd123".isaln
um()Output:True
>>”abcd@123#”.isalnum()
Output: False
>>import re
>>bool(re.match(‘[A-Za-z0-
9]+$','abcd123’))Output:True
>> bool(re.match(‘[A-Za-z0-
9]+$','abcd@123’))Output: False
13. HowWillYouMergeElementsinaSequence?
• Lists
• Tuples
• Strings
ExampleofLists-
>>l1=[1,2,3]
>>l2=[4,5,6]
>>l1+l2
Output: [1,2,3,4,5,6]
ExampleofTuples-
>>t1=(1,2,3)
>>t2=(4,5,6)
>>t1+t2
Output: (1,2,3,4,5,6)
Example of String -
>>s1=“Simpli”
>>s2=“learn”
>>s1+s2
Output: ‘Simplilearn’
14. HowWouldYouRemoveAllLeadingWhitespaceinaString?
Python provides the inbuilt function lstrip() to remove all leading spaces from a string.
>>“ Python”.lstrip
Output:Python
15. HowWouldYouReplaceAllOccurrencesofaSubstringwith
a New String?
The replace() function can be used with strings for replacing a substring with a given
string.Syntax:
str.replace(old,new,count)
string.Example -
you, John?
16. WhatIstheDifferenceBetweenDelandRemove()onLists?
del remove()
• delremovesallelementsofalistwithinagive • remove()removesthefirstoccurrenceofapar
nrange ticularcharacter
• Syntax:dellist[start:end] • Syntax:list.remove(element)
>>del lis[1:3]
>>lis
Output: [“a”,”d”]
>>lis=[‘a’,‘b’,‘b’,‘d’]
>>lis.remove(‘b’)
>>lis
Note that in the range 1:3, the elements are counted up to 2 and not 3.
17. HowDoYouDisplaytheContentsofaTextFileinReve
rse Order?
Youcandisplaythecontentsofatextfileinreverseorderusingthefollowingsteps:
• Openthefileusingtheopen()function
• Storethecontentsofthefileinalist
• Reversethecontentsofthelist
• Runaforlooptoiteratethroughthelist
append() extend()
• append()addsanelementtotheendoftheli • extend()addselementsfromaniterabletot
st heendofthelist
• Example- • Example-
>>lst=[1,2,3] >>lst=[1,2,3]
>>lst.extend([4,5,6])
>>lst.append(4)
>>lst
>>lst
Output:[1,2,3,4]
Output:[1,2,3,4,5,6]
19. WhatIstheOutputofthebelowCode?JustifyYourAnswer.
>>defaddToList(val,list=[]):
>>list.append(val)
>>returnlist
>>list1=addToList(1)
>>list2=addToList(123,[])
>>list3=addToList('a’)
list3)Output:
list1 =
[1,’a’]list2 =
[123]lilst3=[
1,’a’]
Notethatlist1andlist3areequal.WhenwepassedtheinformationtotheaddToList,wediditwithout a
second value. If we don't have an empty list as the second value, it will start with anempty
list, which we then append. For list2, we appended the value to an empty list, so itsvalue
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
callnumber.
20. WhatIstheDifferenceBetweenaListandaTuple?
immutable.Example:
List
>>lst = [1,2,3]
>>lst[2] = 4
>>lstOutput:[
1,2,4]Tuple
>>tpl = (1,2,3)
>>tpl[2] = 4
>>tpl
Output:TypeError:'tuple'
Thereisanerrorbecauseyoucan'tchangethetuple123into124.Youhavetocompletely
reassign the tuple to a new value.
Example-
def add(a,b):
"sum=a+b
return
sumsum=add(1
0,20)
)print("
Output -
main
:add(a,
b)
22. HowDoYouUsePrint()WithouttheNewline?
using.Python v2
>>print(“Hi. ”),
>>print(“How are
you?”)Output: Hi. How
are you?Pythonv3
>>print(“Hi”,end=“ ”)
>>print(“How are
you?”)Output:Hi.Howare
you?
23. HowDoYouUsetheSplit()FunctioninPython?
Thesplit()functionsplitsastringintoseveralstringsbasedonaspecificdelimiter.Syntax
string.split(delimiter,
max)Where:
the delimiter is the character based on which the string is split. By default it is
Example -
>>var=“Red,Blue,Green,Orange”
>>lst=var.split(“,”,2)
>>print(lst)
Output:
[‘Red’,’Blue’,’Green, Orange’]
Here, we have a variable var whose values are to be split with commas. Note that ‘2’
indicatesthat only the first two values will be split.
Pythonisconsideredamulti-paradigmlanguage.
Python follows the object-oriented paradigm
• Pythonallowsthecreationofobjectsandtheirmanipulationthroughspecificmethods
• ItsupportsmostofthefeaturesofOOPSsuchasinheritanceandpolymorphism
• Functionsmaybeusedasthefirst-classobject
• PythonsupportsLambdafunctionswhicharecharacteristicofthefunctionalparadigm
25. WriteaFunctionPrototypeThatTakesaVariableNu
mber of Arguments.
def function_name(*list)
>>def fun(*var):
>> for i
invar:print(i)
>>fun(1)
>>fun(1,25,6)
In the above code, * indicates that there are multiple arguments of a variable.
*args
• Itisusedinafunctionprototypetoacceptavaryingnumberofarguments.
• It'saniterableobject.
• Usage-deffun(*args)
*kwargs
• Itisusedinafunctionprototypetoacceptthevaryingnumberofkeywordedarguments.
• It'saniterableobject
• Usage-deffun(**kwargs):
fun(colour=”red”.units=2)
Itmeansthatafunctioncanbetreatedjustlikeanobject.Youcanassignthemtovariables,orpassthema
sargumentstootherfunctions.Youcanevenreturnthemfromotherfunctions.
name is a special variable that holds the name of the current module. Program execution
startsfromthemainorcodewith0indentations.Thus,name hasavaluemain in the above
case.Ifthefileisimportedfromanothermodule,name holdsthenameofthismodule.
Matrices Arrays
• Amatrixcomesfromlinearalgebraandisatwo- • Anarrayisasequenceofobjectsofsimil
dimensionalrepresentationofdata ardatatype
• It comes with a powerful set of • Anarraywithinanotherarrayforms
mathematicaloperationsthatallowyoutoman amatrix
ipulatethe
dataininterestingways
31. HowDoYouGetIndicesofNMaximumValuesinaNum
py Array?
>>import numpy as np
>>arr=np.array([1, 3, 2, 4, 5])
>>print(arr.argsort()[-N:][::-1])
32. HowWouldYouObtaintheRes_setfromtheTrai
n_setandtheTest_setfromBelow?
>>train_set=np.array([1, 2, 3])
Res_set[[1,2,3],[0,1,2],[1,2,3]]
1. res_set=train_set.append(test_set)
2. res_set=np.concatenate([train_set,test_set]))
3. resulting_set=np.vstack([train_set,test_set])
4. Noneofthese
Here, options a and b would both do horizontal stacking, but we want vertical stacking. So,
optionc is the right statement.
33. HowWouldYouImportaDecisionTreeClassifierinSkle
arn? Choose the Correct Option.
1. fromsklearn.decision_treeimportDecisionTreeClassifier
2. fromsklearn.ensembleimportDecisionTreeClassifier
3. fromsklearn.treeimportDecisionTreeClassifier
4. Noneofthese
Answer-3.fromsklearn.treeimportDecisionTreeClassifier
Wecanusethefollowingcode:
>>link = https://docs.google.com/spreadsheets/d/...
>>source = StringIO.StringIO(requests.get(link).content))
>>data = pd.read_csv(source)
35. WhatIstheDifferenceBetweentheTwoDataSeriesGiv
en Below?
df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name',
1. 1istheviewoftheoriginaldataframeand2isacopyoforiginaldataframe
2. 2istheviewoftheoriginaldataframeand1isacopyoforiginaldataframe
3. Botharecopiesoforiginaldataframe
4. Bothareviewsoforiginaldataframe
36. YouGettheError“temp.Csv”WhileTryingtoReadaFileUsin
g Pandas. Which of the Following Could Correct It?
Error:
Traceback(mostrecentcalllast):File"<input>",line1,in<module>UnicodeEncodeError:
'ascii'codeccan'tencodeacharacter.Ch
1. pd.read_csv(“temp.csv”,compression=’gzip’)
2. pd.read_csv(“temp.csv”,dialect=’str’)
3. pd.read_csv(“temp.csv”,encoding=’utf-8′)
4. Noneofthese
Theerrorrelatestothedifferencebetweenutf-
8codingandUnicode.Sooption3.pd.read_csv(“temp.csv”,encoding=’utf-
8′)cancorrectit.
37. HowDoYouSetaLineWidthinthePlotGivenBelow?
>>plt.plot([1,2,3,4])
>>plt.show()
1. Inlinetwo,writeplt.plot([1,2,3,4],width=3)
2. Inlinetwo,writeplt.plot([1,2,3,4],line_width=3
3. Inlinetwo,writeplt.plot([1,2,3,4],lw=3)
4. Noneofthese
Answer - 3. In line two, write plt.plot([1,2,3,4], lw=3)
38. HowWouldYouResettheIndexofaDataframetoaGive
n List? Choose the Correct Option.
1. df.reset_index(new_index,)
2. df.reindex(new_index,)
3. df.reindex_like(new_index,)
4. Noneofthese
Answer - 3. df.reindex_like(new_index,)
39. HowCanYouCopyObjectsinPython?
copy.copyforshallowcopyandco
py.deepcopy()fordeepcopy
xrange()
range()
41. HowCanYouCheckWhetheraPandasDataframeIsEm
pty or Not?
The attribute df.empty is used to check whether a pandas data frame is empty or not.
>>importpandasaspd
>>df=pd.DataFrame({A:[]})
>>df.empty
Output:True
42. WriteaCodetoSortanArrayinNumpybythe(N-
1)th Column.
This can be achieved by using argsort() function. Let us take an array X; the code to sort
the(n-1)th column will be x[x [: n-2].argsoft()]
>>import numpy as np
>>X=np.array([[1,2,3],[0,5,2],[2,3,4]])
>>X[X[:,1].argsort()]Output:array([[
1,2,3],[0,5,2],[2,3,4]])
43. HowDoYouCreateaSeriesfromaList,NumpyArra
y,andDictionary?
>> #Input
>>import numpy as np
>>import pandas as pd
>>mylist = list('abcedfghijklmnopqrstuvwxyz’)
>>myarr = np.arange(26)
>>ser1 = pd.Series(mylist)
>>ser2 = pd.Series(myarr)
>>ser3 = pd.Series(mydict)
>>print(ser3.head())
44. HowDoYouGettheItemsNotCommontoBothSeriesA
and Series B?
>> #Input
>>import pandas as pd
>> #Solution
>>ser_u[~ser_u.isin(ser_i)]
45. HowDoYouKeepOnlytheTopTwoMostFrequentValuesasItI
sandReplaceEverythingElseas‘other’inaSeries?
>> #Input
>>import pandas as pd
>>np.random.RandomState(100)
>>ser = pd.Series(np.random.randint(1, 5, [12]))
>> #Solution
>>print("Top2Freq:",ser.value_counts())
>>ser[~ser.isin(ser.value_counts().index[:2])]='Other’
>>ser
46. HowDoYouFindthePositionsofNumbersThatAre
Multiples of Three from a Series?
>> #Input
>>import pandas as pd
>>ser
>>#Solution
>>print(ser)
>>np.argwhere(ser%3==0)
47. HowDoYouComputetheEuclideanDistanceBetweenTw
oSeries?
>> #Input
>>sum((p - q)**2)**.5
>> #Solution
usingfunc
>>np.linalg.norm(p-q)
YoucanseethattheEuclideandistancecanbecalculatedusingtwoways.
48. HowDoYouReversetheRowsofaDataFrame?
>> #Input
>> #Solutio
n>>df.iloc[::-1,
:]
49. IfYouSplitYourDataintoTrain/TestSplits,IsItPos
sibletooverFit YourModel?
Yes.Onecommonbeginnermistakeisre-
tuningamodelortrainingnewmodelswithdifferentparameters after seeing its performance on the
test set.
50. WhichPythonLibraryIsBuiltonTopofMatplotliband
Pandas to Ease Data Plotting?
Seaborn is a Python library built on top of matplotlib and pandas to ease data plotting. It is a
datavisualization library in Python that provides a high-level interface for drawing
statisticalinformative graphs.
Any programming language that is not in machine-level code before runtime is called
aninterpreted language. Python is thus an interpreted language.
PEP denotes Python Enhancement Proposal. It's a collection of guidelines for formatting
Pythoncodefor maximum readability.
Decorators are used for changing the appearance of a function without changing its
structure.Decorators are typically defined before the function they are enhancing.
Decorators are typically defined before the function they are enhancing. To use a decorator,
wemust first specify its function. Then we write the function to which it is applied, simply placing
thedecorator function above the function to which it must be applied.
58. Differentiatebetween.pycand.py.
The.pyfilesarethesourcecodefilesforPython.ThebytecodeofthePythonfilesisstoredin
.pycfiles,whicharecreatedwhencodeisimportedfromanothersource.Theinterpretersavestime by
converting the source .py files to .pyc files.
Slicing is a technique for gaining access to specific bits of sequences such as strings, tuples,
andlists.
Slicing is a technique for gaining access to specific bits of sequences such as lists, tuples,
andstrings. The slicing syntax is [start:end:step]. This step can also be skipped. [start:end]
returns allsequence items from the start (inclusive) to the end-1 element. It means the ith
element from theend of the start or end element is negative i. The step represents the jump or
the number ofcomponents that must be skipped.
In Python, keywords are reserved words with a specific meaning. They are commonly used
tospecifythetypeofvariables.Variableandfunctionnamescannotcontainkeywords.Followingarethe
33 keywords of Python:
• Yield
• For
• Else
• Elif
• If
• Not
• Or
• And
• Raise
• Nonlocal
• None
• Is
• In
• Import
• Global
• From
• Finally
• Except
• Del
• Continue
• Class
• Assert
• With
• Try
• False
• True
• Return
• Pass
• Lambda
• Def
• As
• Break
• While
• Concatenatingthembyverticallystackingthetwodataframes.
• Concatenatingthembyhorizontallystackingthetwodataframes.
• Puttingthemtogetherinasinglecolumn.
63. What are the key features of the Python 3.9.0.0 version?
• Optimizationsincludeimprovedidiomforassignment,signalhandling,andPythonbuilt-
ins.
• Pythonalsoincludesabuilt-ingarbagecollector,whichrecyclesallunusedmemoryand
makes it available to the heap space.
65. ExplainPYTHONPATH.
It's an environment variable that is used when you import a module. When a module is
imported,PYTHONPATHischeckedtoseeiftheimported modules are present in various folders. It
isused by the interpreter to determine which module to load.
66. Explain global variables and local variables in Python.
LocalVariables:Alocalvariableisanyvariabledeclaredwithinafunction.Thisvariableexistsonly in
local space, not in global space.
GlobalVariables:Globalvariablesarevariablesdeclaredoutsideofafunctionorinaglobalspace.
Yes,Pythoniscase-sensitive.
68. HowtoinstallPythononWindowsandsetpathvariables?
• DownloadPythonfromhttps://www.python.org/downloads/
• Installitonyourcomputer.Usingyourcommandprompt,lookforthelocationwherePYTHONisinstalled
onyourcomputerbytypingcmdpython.
• Then,inadvancedsystemsettings,createanewvariablecalledPYTHON_NAMEandpastethecopi
edpathintoit.
• Searchthepathvariable,chooseitsvalue,andselect‘edit’.
• Ifthevaluedoesn'thaveasemicolonattheend,addone,andthentype%PYTHONHOME%.
Indentation is required in Python. It designates a coding block. An indented block contains all
ofthecodeforloops,classes,functions,andsoon.Typically,fourspacecharactersareused.Yourcodew
illnot executecorrectlyifit isnotindented, anditwillalso generateerrors.
Self is used to represent the class instance. In Python, you can access the class's attributes
andmethods with this keyword. It connects the attributes to the arguments. Self appears in a
varietyof contexts and is frequently mistaken for a term. Self is not a keyword in Python, unlike
in C++.
For primitive data types, a literal in Python source code indicates a fixed value.
For primitive data types, a literal in Python source code indicates a fixed value. Following are
the5 types of literal in Python:
• String Literal: A string literal is formed by assigning some text to a variable that is contained
insingle or double quotes. Assign the multiline text encased in triple quotes to produce
multilineliterals.
• NumericLiteral:Theymaycontainnumericvaluesthatarefloating-
pointvalues,integers,orcomplexnumbers.
• CharacterLiteral:Itismadebyputtingasinglecharacterindoublequotes.
• BooleanLiteral:TrueorFalse
• LiteralCollections:Therearefourtypesofliteralssuchaslistcollections,tupleliterals,setliterals,d
ictionaryliterals,andsetliterals.
Python modules are files that contain Python code. Functions, classes, or variables can be used
inthis code. A Python module is a .py file that contains code that may be executed. The following
arethe commonly used built-in modules:
• JSON
• datatime
• random
• math
• sys
• OS
_init_ is a constructor or method in Python. This method is used to allocate memory when
anew object is created.
A lambda function is a type of anonymous function. This function can take as many
parametersas you want, but just one statement.
• AssigningLambdafunctionstoavariable
• WrappingtheLambdafunctionintoanotherfunction
79. WhatarePythoniterators?
Intermsoffunctionality,xrange,andrangeareessentiallythesame.Theybothprovideyoutheoption of
generating a list of integers to use whatever you want. The sole difference betweenrange and
xrange is that range produces a Python list object whereas x range returns anxrange object.
This is especially true if you are working with a machine that requires a lot ofmemory, such as
a phone because range will utilize as much memory as it can to generateyour array of
numbers, which can cause a memory error and crash your program. It is a beastwith a memory
problem.
The Pickle module takes any Python object and converts it to a string representation, which it
thendumps into a file using the dump method. This is known as pickling. Unpickling is the process
ofrecovering original Python objects from a stored text representation.
The assignment statement (= operator) in Python does not copy objects. Instead, it establishes
aconnection between the existing object and the name of the target variable. The copy module
isused to make copies of an object in Python. Furthermore, the copy module provides two
optionsfor producing copies of a given object –
Deep Copy: Deep Copy recursively replicates all values from the source to the
destinationobject, including the objects referenced by the source object.
fromcopyimportcopy,deepcopylis
## shallow
copylist_2 =
copy(list_1)list_2[3]
7list_2[2].append(6)
4]##deep copy
list_3 = deepcopy(list_1)
list_3[3] =
8list_3[2].append(
7)
list_3 #output=>[1,2,[3,5,6,7],8]
list_1 #output=>[1,2,[3,5,6],4]
Shallow Copy: A bit-wise copy of an object is called a shallow copy. The values in the
copiedobject are identical to those in the original object. If one of the values is a reference to
anotherobject, only its reference addresses are copied.
84. InPython,areargumentsprovidedbyvalueorreference?
Pass by value: The actual item's copy is passed. Changing the value of the object's copy
doesnotaffect the original object's value.
Pass by reference: The actual object is passed as a reference. The value of the old
objectwill change if the value of the new object is changed.
Python.def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
3]appendNumber(arr)
The join() function can be used to combine a list of strings based on a delimiter into a
singlestring.
Thesplit()functioncanbeusedtosplitastringintoalistofstringsbasedonadelimiter.string =
"This is a string."
*args
• Thefunctiondefinitionusesthe*argssyntaxtopassvariable-lengthparameters.
• "*"denotesvariablelength,while"args"isthestandardname.Anyotherwillsuffice.
**kwargs
• **kwargsisaspecialsyntaxforpassingvariable-lengthkeywordedargumentstofunctions.
• Whenavariableispassedtoafunction,itiscalledakeywordedargument.
• "kwargs"isalsousedbyconventionhere.Youarefreetouseanyothername.
88. What are negative indexes and why are they used?
• Theindexesfromtheendofthelist,tuple,orstringarecallednegativeindexes.
• Arr[-1]denotesthearray'slastelement.Arr[]
Thecapitalize()functioninPythoncapitalizesastring'sinitialletter.Itreturnstheoriginaltextifthe string
already contains a capital letter at the beginning.
Comments that involve multiple lines are known as multi-line comments. A # must prefix all
linesthat will be commented. You can also use a convenient shortcut to remark several lines. All
youhave to do is hold down the ctrl key and left-click anywhere you want a # character to
appear,theninput a# once. Thiswill adda commentto every linewhere youput your cursor.
92. What are docstrings?
Docstrings are documentation strings. Within triple quotations are these docstrings. They are
notallocated to any variable and, as a result, they can also be used as comments.
Special functions are known as operators. They take one or more input values and output a
94. Whatarethefunctionshelp()anddir()usedforinPython?
Both help() and dir() are available from the Python interpreter and are used to provide
acondensed 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
toaccess help for modules, keywords, attributes, and other items.
95. Whyisn'tallthememoryde-allocatedwhenPythonexits?
• When Python quits, some Python modules, especially those with circular references
toother objects or objects referenced from global namespaces, are not necessarily freed
ordeallocated.
• Python would try to de-allocate/destroy all other objects on exit because it has its
ownefficientcleanup mechanism.
• Itisdifficulttode-allocatememorythathasbeenreservedbytheClibrary.
96. What is a dictionary in Python?
TheTernaryoperatoristheoperatorfordisplayingconditionalstatements.Thisismadeoftrueorfalse
values and a statement that must be evaluated.
Python's "re" module provides three ways for modifying strings. They
subn(): It works similarly to sub(), returning the new string as well as the number of
replacements.sub(): identifies all substrings that match the regex pattern and replaces them with
a new string
Pythonsequencesareindexed,andtheyincludebothpositiveandnegativevalues.Positivenumbersar
eindexedwith'0'asthefirstindexand'1'asthesecondindex,andsoon.
The index for a negative number begins with '-1,' which is the last index in the sequence
andends with '-2,' which is the penultimate index, and the sequence continues like a
positivenumber. The negative index is used to eliminate all new-line spaces from the string and
allow itto accept the last character S[:-1]. The negative index can also be used to represent the
correctorder of the string.
PackagesinPythonarenamespacesthatcontainnumerousmodules.
101. What are built-in types of Python?
• Built-infunctions
• Boolean
• String
• Complexnumbers
• Floatingpoint
• Integers
• NumPyarraysarefaster,andNumPycomeswithseveralfeatures,includinghistograms,algebr
a,linear,basicstatistics,fastsearching,convolutions,FFTs,andmore.
Theappend(),extend(),andinsert(i,x)procedurescanbeusedtoaddelementstoanarray.
104. What is the best way to remove values from a Python array?
Thepop()andremove()methodscanbeusedtoremoveelementsfromanarray.Thedifferencebetweenthese
twofunctionsisthatonereturnstheremovedvaluewhiletheotherdoesnot.
105. Is there an object-oriented programming
(OOPs)concept in Python?
Python is a computer language that focuses on objects. This indicates that by simply
constructingan object model, every program can be solved in Python. Python, on the other hand,
may be usedas both a procedural and structured language.
106. Differentiatebetweendeepandshallowcopy.
When a new instance type is formed, a shallow copy is used to maintain the values that
werecopied in the previous instance. Shallow copy is used to copy reference pointers in the
sameway as values are copied. These references refer to the original objects, and any
modificationsmadetoanymemberoftheclasswillhaveanimpactontheoriginalcopy.Shallowcopyenab
lesfaster program execution and is dependent on the size of the data being utilized.
Deep copy is a technique for storing previously copied values. The reference pointers to
theobjects are not copied during deep copy. It creates a reference to an object and stores the
newobjectthatisreferencedtoanotherobject.Thechangesmadetotheoriginalcopywillnotaffectany
subsequent copies that utilize the item. Deep copy slows down program performance
bycreating many copies of each object that is called.
APythonlibraryisagroupofPythonpackages.Numpy,Pandas,Matplotlib,Scikit-learn,andmany
other Python libraries are widely used.
• Asthishappenssoquickly,itmayappeartothehumaneyethatyourthreadsarerunning
in parallel, but they are actually sharing the same CPU core.
• The Global Interpreter Lock is a Python concept (GIL). Only one of your 'threads'
canexecute at a moment, thanks to the GIL. A thread obtains the GIL, performs
somework, and then passes the GIL to the following thread.
A dataframe is a 2D changeable and tabular structure for representing data with rows
andcolumns labeled.
Monkey patches are solely used in Python to run-time dynamic updates to a class or module.
Inheritance allows one class to gain all of another class's members (for example, attributes
andmethods). Inheritance allows for code reuse, making it easier to develop and
maintainapplications.
• Singleinheritance:Themembersofasinglesuperclassareacquiredbyaderivedclass.
• Multiple inheritance: More than one base class is inherited by a derived class.
A class can be inherited from multiple parent classes, which is known as multiple inheritance.
Incontrast to Java, Python allows multiple inheritance.
The ability to take various forms is known as polymorphism. For example, if the parent class has
amethod named ABC, the child class can likewise have a method named ABC with its
ownparameters and variables. Python makes polymorphism possible.
Encapsulation refers to the joining of code and data. Encapsulation is demonstrated through
aPython class.
Onlythenecessarydetailsareprovided,whiletheimplementationishiddenfromview.Interfacesand
abstract classes can be used to do this in Python.
Access to an instance variable or function is not limited in Python. To imitate the behavior
ofprotected and private access specifiers, Python introduces the idea of prefixing the name of
thevariable, function, or method with a single or double underscore.
A class that has no code defined within its block is called an empty class. The pass keyword
canbe used to generate it. You can, however, create objects of this class outside of the class.
Whenusedin Python, thePASS command has noeffect.
122. What does an object() do?
It produces a featureless object that serves as the foundation for all classes. It also does
notaccept any parameters.
def pyfunc(r):
1
forxinrange(r):
2
print(' '*(r-x-1)+'*'*(2*x+1))
3
pyfunc(9)
4
Output:
***
*****
*******
*********
***********
*************
***************
*****************
124. Writeaprogram toproduce theFibonacciseries inPython.
# Enterthenumberof
1 terms
needednbsp;#0,1,1,2,3,5....
2
a=int(input("Enter the terms"))
3
f=0;#first element of series
4
s=1#second element of series
5
if a=0:
6
print("Therequestedseriesis",f)
7
else:
8
print(f,s,end=" ")
9
for x in range(2,a):
10
print(next,end=" ")
11
f=s
12
s=next
a=input("enter sequence")
b=a[::-1]
if a==b:
print("palindrome")
else:
print("Not a Palindrome")
2 count = 0
3 text = fh.read()
5 ifcharacter.isupper():
6 count += 1
character.isupper())
1
127. Canyouwriteasortingalgorithmwithanumericaldataset?
list=["1","4","0","6","9"]
1
list.sort()
3
print (list)
4
128. Checkthecodegivenbelow,andlistthefinalvalueofA0,
A1 …An.
1 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
4 A4 = [i for i in A1 if i in A3]
7 print(A0,A1,A2,A3,A4,A5,A6)
Here’stheanswer:
A1=range(0,10)
A2=[]
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
FlaskisaPythonwebmicroframeworkbasedontheBSDlicense.TwoofitsdependenciesareWerkzeu
g and Jinja2. This means it will have few if any, external library dependencies. Itlightens the
framework while reducing update dependencies and security vulnerabilities.
A session is just a way of remembering information from one request to the next. A session in
aflask employs a signed cookie to allow the user to inspect and edit the contents of the session.
Iftheuseronlyhasthesecretkey,heorshecanchangethesession.Flask.secretkey.
Django and Flask map URLs or addresses entered into web browsers into Python functions.
Flask is easier to use than Django, but it doesn't do much for you, so you will have to specify
thespecifics, whereas Django does a lot for you and you won't have to do anything. Django
hasprewritten code that the user must examine, whereas Flask allows users to write their
code,making it easier to grasp. Both are technically excellent and have their own set of
advantagesand disadvantages.
• Pyramid is designed for larger apps. It gives developers flexibility and allows them
toutilizetheappropriatetoolsfortheirprojects.Thedatabase,URLstructure,templatingstyle
,andotheroptionsareallavailabletothedeveloper.Pyramidscanbeeasily customized.
132. InNumPy,howwillyoureadCSVdataintoanarray?
Thismaybeaccomplishedbyutilizingthegenfromtxt()methodwithacommaas thedelimiter.
The term GIL stands for Global Interpreter Lock. This is a mutex that helps
threadsynchronization by preventing deadlocks by limiting access to Python objects. GIL
assists withmultitasking (and not parallel computing).
PIP denotes Python Installer Package. It is used to install various Python modules. It's
acommand-line utility that creates a unified interface for installing various Python modules.
Itsearches the internet for the package and installs it into the working directory without
requiringany user intervention.
136. Writeaprogramthatchecksifallofthenumbersin a
sequence are unique.
def check_distinct(data_list):
if len(data_list) ==
len(set(data_list)):returnTrue
else:
returnFalse;
print(check_distinct([1,6,5,8])) #Prints
Trueprint(check_distinct([2,2,5,5,7,8]))#PrintsF
alse
• Bitwise operators
• Identity operators
• Membership operators
• Logical operators
• Assignment operators
• Relational operators
• Arithmetic operators
The old Unicode type has been replaced with the "str" type in Python 3, and the string
isnow considered Unicode by default. Using the art.title.encode("utf-8") function, we
cancreate a Unicode string.
Python3.x?
Python2.xisanolderversionofthePythonprogramminglanguage.Python3.xisthemostrecentversion.Pyth
on2.xisnolongersupported.Python3.xisthelanguage'spresentandfuture.
InPython2,astringisinherentlyASCII,whileinPython3,itisUnicode.
141. How to send an email in Python language?
Python includes the smtplib and email libraries for sending emails. Import these modules into
thenewly generated mail script and send mail to users who have been authenticated.
while num2 != 0:
num2num1 = num1 ^
return
num1print(add_nums(2,
10))
import re
def transform_date_format(date):
date)date_input = "2021-08-
01"print(transform_date_format(date_input))
The datetime module can also be used, as demonstrated below:
from datetime import datetime
new_date=datetime.strptime("2021-08-01","%Y-%m-
%d").strftime("%d:%m:%Y")print(new_data)
new_dict = Counter(d1) +
Counter(d2)print(new_dict)
No.
TherearefourjoinsinPandas:left,inner,right,andouter.
The type and fields of the dataframes being merged determine how they are merged. If
thedata has identical fields, it is combined along axis 0, otherwise, it is merged along axis
1.
148. What is the best way to get the first five entries of
adata frame?
Wemaygetthetopfiveentriesofadataframeusingthehead(5)method.df.head()returnsthetop 5 rows
by default. df.head(n) will be used to fetch the top n rows.
149. Howcanyouaccessthedataframe'slatestfiveentries?
Wemaygetthetopfiveentriesofadataframeusingthetail(5)method.df.tail()returnsthetop5rows by
default. df.tail(n) will be used to fetch the last n rows.
150. Explainclassifier.
Anydatapoint'sclassispredictedusingaclassifier.Classifiersarehypothesesthatareusedtoassign
labels to data items based on their classification.