You are on page 1of 35
1219/21, 9:46 AM ‘Top Python Interview Que ns (2021) -Interviewsit seater Mock nine Ber interviewSt Kasey Practice Contests TN. log (n® — Community 0 G50 K_ Kunal Free Mock Assessment Looking to crack SDE Interviews? Get personalised Learning Plan for FREE! Take Mock Assessment 115000+ Developers Registered! x Python Interview Questions Downloadpor "aN gw Introduction to Pythor Python Interview Python was developed by Guido van Rossum and was released fst on February 20, 1991, tis one ofthe most widely-4 vramming languages and is interpreted in nature thereby providing flexibility of incorporating dynamic semantics. | ‘source language with vey simple and clean syntax. This makes it developers easy to learn python. Python also st ramming and is most commonly used to perform general-purpose programming x tots simplistic nature and the abit to achieve multiple functionalities in fewer lines of code, python’ popularity Supercharge your tech endoush, Python is also used in Machine Learning, rtf Intligence, Web Development, Web Scraping, and va career! tots abilty to suppor powerful computation using powerful ibraies. Duet this, there isa huge demand for py atterethe ‘and across the world, Companies are wiling to offer amazing perks and benefits to these developers. FREE live class is article, we will see the most commonly asked python interview questions and answers which wil help you excel ‘00k Now Got sugsestons ? We would lve to hear your feedback hitpslwwcinterviewbit.comipython-intervew-questions! 115 1219/21, 9:46, AM 4, What isan Interpreted language? [What is PEP 8 and why is it immporent? [what is Scope in Python? [What ar lists and ‘tuples? What is the key difference between the twa? 8, What are the common builtin data types in Python? 9, What is pass in ‘Top Python Interview Questions (2021) ‘+ Python Interview Questions for Freshers ‘+ Python Interview Questions for Experienced. ‘+ Python OOPS Interview Questions Get Ready with Free Mock Coding Interview Know More = ‘Python Pandas Interview Questions ‘© Numpy Interview Questions ‘Python Libraries Interview Questions ‘+ Python Programming Examples Python interview Questions and Answers (2020) | Python |. Python? 10. What are modules and Python Interview Questions for Freshers 1. What is Python? Python i @ high-level, interpreted, general-purpose programming language. Being a general-purpose language, it an any type of application with the right tools/librares. Additionally, python supports abjects, modules, thveads,exceptiot automatic memory management which hep in modeling real-world problems and building applications to solve these 2. What are the benefits of using Python? «+ Python isa general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readé reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-sou party packages encouraging modularity and code reuse. + ls high-level data structures, combined with dynamic typing and dynamic binding, attrac a huge community of ‘Application Development and deployment. 3. What is a dynamically typed language? Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-chee languages. tn strongly-typed ianguage, such as Python, "1" + 2 wil esutin a type eror since these languages don coercion® {implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, il sim) 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, dri Python is 2 Dynamically Typed Language. x ‘Supercharge your tech career! Attercthe FREE live class Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 2135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) «thts interviewsit Statically Typed Dynamically Typed ‘You can download a PDF version of Python Interview Questions. ‘4, What is an Interpreted language? [An Interpreted language executes is statements line by line, Languages such as Python, Javascriot,R, PHP, ard Ruby a Incerpreted languages. Programs written in interpreted language runs directly from the source code, with no interm 5. What is PEP 8 and why is it important? PEP stands for Python Enhancement Propasal. A PEP isan official design document providing information tothe Pytt describing 2 new feature for Python or its processes, PEP 8 is especially important since it documents the siyle guidelt [Apparently contributing to the Python open-source cammunity requires you to follow these style guidelines sincerely ¢ 6. What is Scope in Python? Every obj in Python functions within a scope. A scope is a block af code where an object in Python remains relevant identity all the objects insce @ program. However, these namespaces also have a scape defined for them where you co without any prefix A few examples of scope created during code execution in Python are a follows 1+ Alocal 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 inthe program ‘+ An outermost scope refers to all the bul referenced, Note: Local scape objects can be synced with glabal scape objects using keywords such as global names callable in the program. The objects inthis scope are searchey 7. What are and tuples? What is the key difference between the two? Lists and Tuples are both sequence data types that can store a collection of abjecs in Python. The objects stored in E have diferent data types. Lists are represented with square brackets ['sars', 6, 9.39] , while tuples are represen 188s 5 8.97) ‘uhat isthe real diference between the two? The key difference between the two is that while lists are mutable, tu ‘mmutable objects This means that sts can be modified, appended or siced on the go but tuples remain constan ified in any manner. You can run the fellowing example on Python IDLE to confirm the difference: Supercharge your tech supe = ('sara’, 6, 5, 8.97) career! ist = (sara, 6, 5, 8.97) attendthe int(ey-tuple(e]) # output => ‘sara FREE live class nt(ny2sst{8]) —# output => “sara tuple[e] = ‘ansh’ —# modifying tuple => throus an error SSt{0} = “ansh’ modifying List = Lise modifies okNow re{oy_suptefO]) output => ‘sara’ Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 3135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) 8, What are the common built-in data types in Python? here are several bull-in datatypes in Python. Although, Python doesn't require data types to be defined explicitly dur ectarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are ny Provides type() and isinstance() functions to check the type of these variables. These data types can be groupe categories + None Type: one keyword represents the nul values in Python, Boolean equality operation can be performed using these Ni Chass Name Description Nonetype Represents the NULL values in Python ‘+ Numerie Types: ‘There are three distinct numeric types - integers, floating-point numbers, and complex numbers. Additionally) type of integers. Class Name Description ine Stores integer ters inelucing hex, etal ane binary nubs 8 integee fst Stores eral contsining decimal values and/or exponent igs as Hating-polt numba complex Stores complex numbars inthe form («and has stibutes real and nag bool ‘Stores boolean value (rue a aie) [Note:The standard library also includes fractions to store rational numbers and decimal to stare floating-point number precision. + Sequence Types: ‘According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence type rot in operators defined for their traversing their elements, These operators shave the same priority a5 the com Class Name Description sn Mutable sequence used to store coletion ofits ‘wple Immutable sequence use to store collection of tems ssnae Represents an inmutsble sequence of numbers generate during execstion ea Immurable sequence of Unicode code points te store textual data, Note: The standard library also inclides additional types for processing: 1. Binary data such 25. bytearray bytes nenoryview , 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 isc) standard mapping type, the dictionary. ‘lass Name Description ict Stores comma-separated tof key: value pis + Set Types: x Currently, Python has two built-in st types ~set and frazenset set type is mutable and supports methods like 3 frozenset type is immutable and can't be mocified after creation. ‘Supercharge your tech set Mutable unorderad collection of distinct hashable object, career ‘ Imotabe callin of sities ehh eccne ronan Inmtabe collecion of tn hashabe obec FREE live class x set is mutable and thus cannot be used as key fora dictionary. On the other hand, frozenset is immutable be used as @ dictionary key or as an element of another set Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 405 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Interviewait + Modules: Module isan additional built-in type supported by the Python Interpreter. supports one special operation |e, al synod.ayob , where ayzod_ isa module and myobj references 2 name defined in m's symbol table, The modu in a very special attribute of the module _diet_, but direct assignment to this module is nether possible nor reco + Callable Types: Callabe types are the types to which function call can be applied. They can be user-defined functions, instance + funetions, and some other built-in funetions, metheds and classes Refer to the documentation at docs.python org for» detailed view ofthe callable types, 9. What is pass in Python? The pass keyword represents 9 null operation in Python. It is generally used forthe purpose of filing up empty bloc! execute during runtime but has yet to be written. Without the pass statement inthe following code, we may run into 8 def nyEnptyFune() do nothing ryenptyFunc() nothing happens fF Fste “estein", ine 10. What are modules and packages in Python? Python packages and Python modules ave two mechanisms that allow for modula in Python, Modula advantages - “Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand, This ‘easier and less error-prone, ‘+ Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they ‘that reduces interdependency, itis less likely that modifications in a madule might impact other parts of he proge ‘+ Reusability: Functions defined in a module can be easily reused by other parts ofthe application. ++ Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifies from ot program, “Modules, in genera, are simply Python files wth a py extension andl can have a set of functions, lasses, or variables 6 implemented. They can be imparted and initalized once using the inport_ statement If partial functionality is neede classes or functions using fron foo iaport bar Packages allow for hirarchal structuring ofthe module namespace using det notation. As, modules help void clast variable names, na similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use ofthe system's inherent file structure. So just stuff the modules into a fol it the folder name as the package name, Importing 3 module ots contents from this package requires the package n ‘module name joined by 2 dot [Note: You can technically import the package as well but alas, doesn't import the modules within the package to the le Is practically useless. ‘11. What are global, protected and private attributes in Python? + Global variables are public variables that are defined inthe global scope To use the variable in the global scope it the gloss keyword + Protected atributes are attributes defined with an underscore prefixed to their identifier eg, sara, They can stil ‘modified from outside the clas they ae defined in but a responsible developer should retrain from doing so, Private attributes are attributes with double underscore prefixed to their identifier eg. _ansh They cannot be aces. X the outside directly and will result in an Attrbutetrrorif such an attempt is made What is self in Python? ‘sa keyword in Python used to define an instance of an object ofa class. In Python, it is explicitly used asthe first ‘Supercharge your tech where itis optional helps in distinguishing beswesn the methods and attributes of s clase fom ts local variable career! ® enn Attenethe What is _init_? FREE live class nit___ is a contructor method in Python and is automatically called to allocate memory when a new object/instan | _init_ method associated with them. I helps in distinguishing methods and attributes ofa class from local var Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 5135, 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) class oof clase Student def _tnkt_(sei¢, frone, Inone, ag6, sectfon) self.age = age cneating 2 new object stu = Student("Sara", “Ansh", 22, "A2*) 14, What is break, continue and pass in Python? Break Theres statement terminates the loop immedistely ac the contol lows othe statement ater the Body of. Continue The continue statement terminates the current te contol ows tothe net tration of th loop ion of he statement sips the ast ofthe code inthe cure Pass Asexpsined above, the pass Keyword in Python is general use to fil up em represented by 2 seri-colon in anguages suchas a3, C+, avaserp ete pet = (2, 3, 2,4 23, 2, 8 By 3) sui (p ¥ 2 = 8) print(p) output > 23232 print(current) & autput => @ 15. What are unit tests in Python? “+ Unit testi a unit testing framework of Python, “+ Unit testing means testing different components of software separately. Can you think about why unit testing i it scenario, you are building software that uses three components namely A, 8, and C. Now, suppose your software E How will you fin which component was responsible far breaking the saftware? Maybe it was component A that fe Ccampanent B, and this actually failed the softwate, There can be many such combinations, ‘+ This is why its necessary to test each and every companent properly so that we know which component might be the failure of the software, 16. What is docstring in Python? ‘+ Documentation sting or docstrng is 8 multi string used to document a specitic code segment. 1+ The docstring should describe what the function or method does, 17. What is slicing in Python? 1 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 alist or tuple + stop isthe ending index or where to sop. + step isthe number of steps jump. ‘+ Default value for starts 0, stop is number of items, step i 1. + ‘Slicing can be done on strings, arrays, lists, and tuples. xobers = (4, 2,3; 4, 5, 6 7, 8, 9 20) rie(nunbersi2 = + 21) soutput + (2, 4, 6, 8, 30] Explain how can you make a Python Script executable on Unix? ‘Supercharge yOUr tech script file must begin wih #/usr/binfenv python career! Atterc the What is the difference between Python Arrays and lists? FREE live class [Arrays in python can only contain elements of same data types ie. data type of array should be homageneous. It language arrays and consumes far less memory than list. Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 205 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Interviewait “+ Lists in python can contain elements of ciferent datatypes ie, datatype of lits can be heterogeneous. It has the consuming large memory. Anport array 2+ areay.array("i", [2 2, 31) for {in 3 print(3, ender") aourpur: 2.23 2 > array.anray("t 25 1, 2 “string ] prints, en [is 2, ‘string’ 1) OUTPUT: Typeerror: an inten sourPur: 4.2 string Python Interview Questions for Experienced 20. How is memory managed in Python? ‘+ Memory management in Python is handled by the Python Memory Manager. The memory allocated by the mani private heap space decicated to Pytnon ll Python objects are stored in this heap and being private, iti inacces) 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. reece Den MMC Cs 21, What are Python namespaces? Why are they used? [A namespace in Python ensures that object names in s program are unique and can be used without any conc. Pythy namespaces as dictionaries with name as key’ mapped to a corresponding ‘object as value’. This allows for multiple na same name and map itto a separate object A few examples of namespaces are as follows “Local Namespace includes local names insde a function, the namespace is temporarily created for function call the function re ‘+ Global Namespace includes names from various imported packages/ modules that are being used inthe current | is crested when the package is imported inthe script and lasts until the execution ofthe script. + Bult ‘The lifecycle of a namespace depends upon the scape of objects they are mapped to, I the scope of an object ends, espace comes to an end. Hence, itsn't possible to access inner namespace objects from an outer namespace. x [Namespace includes builtin functions of core Python and built-in names for various types of exceptions What is Scope Resolution in Python? s Supercharge Your tech seimes objects within the same scope have the same name but function different n such cases, scope resolution career! ‘on automatically. A few examples of such behavior are: Atercthe FREE liveclass Python modules namely ‘math’ and ‘math’ have lot of functions that are common to bath of them = 0100) « To resolve this ambiguity, itis necessary to prefix them with ther respective module, like nath.exp() and caatt Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. Howe? Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 71835 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) ‘treating theirnamespaces as separate identities tenp = 10 global-scope variable def Fane) print temp) print(tenp) — # output = fune() output => 20 print(tenp) # output => 28 his behavior can be overridden using the global keyword inside the function, as shown inthe following exemple’ tenp = 10 global-scope variable def fone) global temp prane(tenp) print(tenp) —# output = func) # output «> 28 Drint(teep) —# output = 23. What are decorators in Python? Decorators in Python ate essentially functions that ada functionality to an existing function in Python without changin function ise They are represented the decorator nane_ in Python and are called in a bottom-up fashion. For exam dof Towereas det wrapper() une = funetion() string lowercase = func. Lover() def splitter_decorator((unctson det wrapper () fone = funetion() string split = func-split() return wrapper xplitter decorator @ this is executed rext lowercase decorator # this is executed first def hel20() return “Helle Honda” ot) # output => [ “hi corator( function) wore! ] ‘The beauty of the decorators lis in the fact that besides adding functionality tothe output of the method, they can ev for functions and can further modify those arguments before passing It to the function itself. The Inner nested functie function, plays a significant role hee. Is implemented to enforce encapsulation and thus, keep itself hidden from thy scorator(unct$on) def wrapper args, 282) ara = aredcopttatsze() arg2 = arg2.capitalize() string hello = function( are: return string. lananes_ecorstor area) x s8ybeldo(nanes, nane2) return “Helio.” + mane» "1 Hello * + mane 6 11? \hello("sara’, “ansh') # output => ‘Mello Sara! Hello Ansht What are Dict and List comprehensions? ‘Supercharge your tech career! ‘on comprehensions, ike decorators, are syntactie sugar constructs that help bulld altered and filtered lists, dict) Atterc the 1 ist dictionary, or et. Using comprehensions saves alot f time and code that might be considerably more verbe FREE live class of code). Le’ check out some examples, where comprehensions can be truly benefit Performing mathematical operations on the entire list Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 835 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) [2 3 5, 7) squared list = [x42 for x in ay List) List conprehension # output > [4,95 28, 49, 1] squared dict = (x:xt*2 for x in ay List) # tet conprehenston output => (28; 422, 25 4,32 95 2 2S 7S ‘+ Performing conditional filtering operations on the entire list myst = (2, 3, 5, 7, a8) soured list = [x2 for x Sn ay List SF x22 I< 8) A List comprehension F output = [9,255 49, 221) squared dict = (a:xt2 for x An ay List £F 142 I= 0) # alee conprehension # output => (915 128, 31 9, $1 25, 7 9) ‘+ Combining multiple lists into one Comprehension allow for multiple iterators and hence, canbe used to combine multiple lists into one e123) b= 17, 8 9) [G+ 9) for (xy) Am 25p(0,b)] & paratlet Steraters # output > [8, 18, 22] uy) for sn 2 for y Amb] a estes tterators F output => [as Ms Cle Be Oe Me Cr Mr Cr Bs Os Ye Gs De Gr De Gs 9D “+ Flattening » multi-dimensional ist A similar approach of nested iterators (as above) can be applied to flatten a mult-dimensional oF work upon its inn ny_tist = [[20,28, 38), (4,50, 68), (70, 88,80)) Asttened = [x For temp An ay_Dist for x An temp] output = (20, 26, 38, 48, 59, 66, 79, 66, 92) Note: List comprehensions have the same effect as the map method in other languages. They follow the mathemati notation rather than map and fier functions in Python. 25. What is lambda in Python? Why is it used? Lambda isan anonymous function in Python, that can accept any numberof arguments, but can only havea single ext {sed in situations requiring an anonymous function fora short ime period, Lambda functions can be used in either of ‘+ Assigning lamba functions oa variable print(nui(2, 5)) # output => 20 ‘+ Wrapping lamba functions inside another function: er myurappern) rulefve = nyrspper(s) print(oulrive(2)) # output => 10 26. How do you copy an object in Python? InPython, the assignment statement ( = operator) does not copy objects, Instead, it creates a binding between the e target variable name. To create copies ofan object in Python, we need to use the copy module. Moreover, there are tw copies for the given abject using the eapy module = Shallow Copy isa bit-wise copy ofan object. The copied object created has an exact copy of the values in the original 25a reference to other objects, just the reference addresses for the same are copied, Copy copies all values recursively from source to target abject. it even duplicates the object x referenced by th ta tt 2 3, shal Supercharge your tech Sha career! %2 = copy(list_t) siete re FREE live class - 22H output > (2, 2, (3, 5, 6), 7) AF output > 12, 2, 1, 5, 61, 4) ok Now e2ep copy Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 9135 1219/21, 9:46, AM “Top Python Interview Questions (2021) - Intervewsit List 3[3] = 8 ist 3[2].append() List output => [oy 25 (3, 5, 6 7Ts 8) Lista output > (4, 2, 13, 5, 61, 4] 27. What is the difference between xrange and range in Python? xrangeO and range() ace quite similar in terms f functionality. They both generate a sequence of integers, wth the 0) angel) returns a Python list, wheres, range) retums an xrange object So how does that make a difference? It sure doss, because unlike ranged, xrange() doesn't generate a static list, iter 190. This technique fs commonly used with an object-type generator and has been termed as "yielding! Yielding is crucial in applications where memory is 2 constraint. Creating a static ist asin range0 can lead toa Yenory conditions, while, xrangel) can hancle it optimally by using just enough memory forthe generator (significantly less in for { An xcange(i8): numbers fron 0 to 8 print $output o123456789 for £ An xronge(s,20): # nunbers fron 2 to & prints output 223456789 for £ in xrange(2, 18, 2): skip by two for next print i output > 13579 Note: range has been deprecated as of Python 3.x Now range does exactly the same as what xrange used t0¢ it was way better to use xtange than the orginal range function in Python 23 28. What is pickling and unpickling? Python library offers feature - serialization out ofthe box. Serislzing an object refers to transforming it into a forma jekle module comes into play. a5 to be able to deserialize it later on, to obtain the orginal abject. Here, the Pic ing: ‘Pickling is the name of the serialization process in Python, Any abject in Python can be serialized into a byte strear in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle ‘objects it has serialized and the serialization is portable across versions 1+ The function used for the above process is pete. dune() Unpick ‘+ Unpieling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the f to memory. ‘+ The function used for the above process is ptckle.1ead() Note: Python has another, mare primitive, serializatian madule called marshall, which exists primarily to support pye f aliffers significantly from the pickle The Pickle Module Pickling >> crostrreee pickledump() ae << Unpickting ttt Pickleoadl) iene ‘Supercharge your tech career! Atercthe FREEliveclass #88: InterviewBit ‘© Gotsussestons? We would lve ta hear your feedback, hitpslwwizinterviewbit.comipython-ntervew-questions! 10135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) - Interviewait Generators are functions that return an iterable collection of items, one a atime, ina set manner. Generators in gent iterators witha different approach. They employ 4 keyword rather than retuon to return a ger Let's ty and build » generator for flbonacci numbers - use of yi det F8b(0) he(p < 0): x Fib(30) create generator object —est_0), for Python, use next() output output => for £ 4m F25(20) print(s) # output > 0122358 30. What is PYTHONPATH in Python? PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for me This is especially useful in maintaining Python libraries that you do not wish to instal inthe global default location, 31, What is the use of help0 and dir) functions? hhelp0) function in Python is used to display the documentation of modules, classes, functions, keywords, et. Ino para relat). function, then an interactive help utility i lunched on the console died) function ties to return a valid lst of attributes and methods ofthe object itis ealled upon. It behaves differently it sims to produce the most relevant data rather than the complete information. “+ For Modules/ibrary objects it returns alist ofall atributes, contained in that module, 1+ For Class Objects, it returns alist of all valid attributes and base attributes. “+ With no arguments passed, i returns alist of attributes in the current scope, 32, What is the difference between .py and .pyc files? + _pyfiles contain the source code of a program. Whereas, pyc file contains the bytecode of your program. We gett compilation of py fle (source code) pyc files are not created forall the fies that you run. Its only created forthe «+ Before executing 3 python program python interpreter checks forthe compiled files. If the file is present, the virtut not foun it checks for py file I found, compiles it to ye file and then python virtual machine executes + Having pyc file saves you the compilation time. 33, How Python is interpreted? ‘+ Python as a language isnot interpreted or compiled, Interpreted or compiled isthe property ofthe implementatio bytecodetset of interpreter readable instructions) interpreted generally + Source code is file with py extension, ‘+ Python compiles the source code to a set of instructions for a virtual machine, The Python interpreter isan implant machine, This intermeciate format is called “bytecode” py source code is fist compiled to give pye which is bytecode. This bytecode can be then interpreted by the offic Time compiler) compiled by PyPy. How are arguments passed by value or by reference in python? ‘Supercharge your tech eee Pas by va: Copy fhe acta bets passed Changing he ale ofthe copy ofthe bet wit hnge Ate uni tan facet the ae ject pea gg teva aft nec aa FREEINedass Panty mfner ttre oe al bet speed Cong eft ow re thar, arguments ara passed by refurene, a, fare tothe acl jets pated Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 11085 1219/21, 9:46, AM sre.append() are = [ty 2 3] print(are)_routput: sependinber (ore) print(are) routput: 35, What are iterators in Python? 1 Aniterator isan object ‘+ Ieremembers its state ie, where its during iteration (see code below to see how) ‘+ _iter_0 method initializes an iterator. ‘+ Tehas a _next_0 method which returs the next item in iteration and points to the next element. Upon reaching t ‘object _next_0 must retutn Stoplteration exception. ‘Its also self-terable, ‘+ erators are objects with which we can iterate over iterable objects like lists, stings, ete, class ArrayList: def init _(seif, nunber_18st) Felfronbors © ruber list def _iter_(seit) dof _pext_(s0i0) Te{setf-pos < len(self.nunbers)) runbers{self.pos ~ 2) obj = AerayListt(2, 2, 3)) = Hter(array_obi) print(next(st)) woutput: 2 print(next(st)) aoutputs 3 printtrexe(t)) siraceback (most recent €2 last) 36. Explain how to delete a file in Python? Use command os.remove(file name) 37. Explain split() and joinQ func! ‘Supercharge your tech career! Attere the FREE live class os.renove( “Changed ile.csv") print(“File Removed!) ns in Python? ‘+ You can use split function to split a string based on a delimiter to list of strings. ++ You can use joing function to join 9 Ist of strings based on a delimiter to give a single string, string = “This 4s a string." string list = string.split(’ ") fdeliniter is ‘space’ character or ¢ ¢ print(String 2ést) foutput: ['This!, "As", 'a', ‘string.") print(* *.foin(stning list)) output: This is & string x What does *args and **kwargs mean? ‘args isa special syntax used in the function definition to pass variable-length arguments. “+ means variable length and “args" isthe name used by convention, You can use any other. multiply(s, b, “arev) arb Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 12135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) hewargs ‘+ “*kwargs is special syntax used in the function definition to pass variable-length keyworded arguments 1+ Here, also, "kwargs" is used just by convention. You can use any other name. ‘+ Keywotded argument means variable that has a name when passed toa function, ‘+ Itis actually a dctionary ofthe variable names and its value, def tenaArgunents(*"oargs): for ky, value in fonargs.itens() printtkey +": " + value) tet2Angunents(argi = "argument 4°, arg2 = "argument 2°, arg} = "argument 3°) angBs angunent 3 39, What are negative indexes and why are they used? ‘+ Negative indexes are the indexes from the end of the stor tuple or string, ‘+ Art{-1] means the last element of array Atl) are = [1 2. 3, 4 5, 6) prant(are{-2]) soutput 6 print(are{-21) soutput § Python OOPS Interview Questions 40. How do you create a class in Python? To create 2 class in python, we use the keyword “class” as shown inthe example below. class Interviewbstemployee: def init__(self, exp_nane) Self-enp_nane = enp_nane fo instantiate or create an object from the class created above, we do the following enp_a-interviewbitemployee(“hr. Employee") To access the name attribute, we jst eal the atribute using the dot operator as shown below: print(enp_s-nane) fo create methods inside the class, we include the methods under the scope ofthe lass 2s shown below: class Interviewbitemployee: def init__(self, enp_nane) Self.enp_nane = enp_nane def antroduce(seif) print(*Hello I an * + self-enp_nane) ‘The self parameter in the init and introduce functions represent the reference tothe current class instance which is use attributes and methods of that clas. The self parameter has to be the frst parameter of any method defined inside the x ‘Iss InterviewbitEmployee can be accessed as shown below: 1 a-introduee() overall program would look like this ‘Supercharge your tech career! vee. Interviewbsteaptoy Atterc the def init__(self, enp_nane) FREE live class Feitenp_nane = enp_none def introduce(seif): ok Now prant(*Hello 1 an * « self.enp_nane) Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 13035 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) - Intervewsit # eneate an object of Interviewoitenployee class copa = Interviewbitemployee("Mr Employee") print(erp_t-enp_nane) print enployee nane fenp_a-introeucet) fintroduce the enployee 41, How does inheritance work in python? Explain it with an example. Inheritance gives the power to a clas to access all attributes and methods of another class. It ais in code reusability @ to maintain applications without redundant code. The das inheriting from another class isa child class or also called a from which a child class derives the members are called parent class oF superclass, Python supports different kinds of inhertance, they ar: + Single Inheritance: Child class derives members of one parent class Single Inheritance tenet parent class class Parentctass: det par_func(sei#): print(“Z am parent class function") f cnsad class class chiléclass(Parentciass): ef chide func(se3#): pring (*I an child clase function") bjt = chisecaaes() bj-par_fune() ob-chile_fonet) ‘+ Multi-level inheritance: The members of the parent class, A, ae inherited by child class which is then inerited by ‘The features ofthe base class and the derived clas are further inherited into the new derived clss,C. Here, Ai th hss ‘Supercharge your tech career! Attere the FREE live class ‘ Gotsuegestions? We would ove to hear your feedback. hitpslwwizinterviewbit.comipython-ntervew-questions! 14035, 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) - Intervewait Base Class ¥ Intermediatory Class Derived Class c Muttilevel Inheritance Senet class & def _indt_(seif, a_nane): class 814) def init__(self, brane, a_nane) Felf.tonane ~ banane A._intt_(self, 9_rane) # chute class cass c(8) def init _(seif,<_nane, brane, arene) B._init_(self, brane, none) def display_nanes( sei) print(“A nane print(*B mane + *, seIF.P rane) print("C mane : *, self.c sane) hja = C{"ehi2d", “internediste', ‘parent") print{obj1.2_rane) ‘ft. dSsplay_nanes() ~ Multiple Inheritance: Tiss achieved when one child class derives members from more than one parent class. Al X classes are inherited in the child cass Supercharge your tech parents career! det parent, fune(se2 Atencthe, print(*is T an first Parent") FREE live class arent chased okNow def parent fane(s02): Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 15135, 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) class chila(varentt, Parent2) det chitd_Fune(se3F): self.parent_fune() self.parent?fune() ja = chitd() obj2-chile_funet) ‘+ Hierarchical Inheritance: When a parent class is derived by more than one child class is called hierarchical inhe def a fune( sei) print(*Z an from the parent class.) class 814) def b fune(sei6) print(“I an fron the first chile.") class c(A) def ¢ fune(sei#) print("E an fron the seconé chilé.") # ontver"s code objt = 60) obi? = C0) obja.2-fune() objt-bofune() child + nethoa obj2.2_fune() obj2-efune() ach 42. How do you access parent members in the child class? Following are the ways using which you can access parent class members within a child class ‘+ By using Parent clase name: You can use the name of the parent clas to access the attributes as showin in the ex rent (object): def _antt_(seif, none) class chile(arent): def _tntt_(seif, none, 26) def atspiay( seit) print(Parent.rone, sei¢.2E6) obj = Chilé(“Interviewbit", 6) aispiay() By using superd: The parent class members can be accessed in child class using the super keyword. vee Parent(object) Supercharge your tech ie tset, nan) career! Teit.nane = mane Atere the FREE live class sss cosaaieavent) def _snie_(se2¢, nane, age): Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 16135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) super(chiid, sei). self.age = 2ge t_{nane) dor stsplay( sei) # hore since super() ss used in the constructor print(seif.nane, self.2ge) fj = Child(“Interviewbit", 6) obj.ctspley() 43. Are access specifiers used in python? Python does not make use of access specifiers specifically ice private, pubic, protected, etc. However, it does not depr Ithas the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore ( the variable names. By default, the variables without prefixed underscores ae public. Example: class Interviewbstemployee: # protected nenbers # private nenbers def init _(s0if, enp_nane, age, branch): “_branen = branch def isplay(): print(seif.enp_nane 6” “esei¢._agee” “esel._braneh) 44, Is it possible to call parent class without its instance creation? Yes, it is possible ifthe base class instantiated by other child classes or ifthe base clas isa static method. 45, How is an empty class created in python? [An empty class does not have any members defined init Is created by Using the pass keyword (the pass command d We can create objects for ths clas outside the class For example- class EnptyClassveno: objsenptycasspeno() bj -nane="Tntervieubit print(*Nane crested= ",obi.nane) outp Name created = Interviewbit X Differentiate between new and override modifiers. ew modifiers used to instruct the compiler to use the new implementation and not the base class function. The lor overriding @ base class function inside the child class. ‘Supercharge your tech upercharBe your tech Way is finalize used? career! aiterethe ize method i used for freeing up the unmanaged resources and clean up before the garbage collection method i FREE liveclass _™ing memory management taste cs What is init method in python? Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 17135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Interviewait The Init method works similarly to the constructors in Java, The method is run as soon as an abject is instantiated. tis any attributes or default behaviour of the ebjec a the time of instantiation, For example: class interviewbitenploy # sit nethod / constructor def init__(self, enp_nane) det antroduce(seif): print(*Hello, Tan", self-eqp_none) ep ‘onp-ntroduce() ‘eviewbiteeployee( Me Enployee') init sethod is called here and initializes the abject na 49, How will you check if a class is a child of another class? This is done by using a method eae true or false accordingly For example: subclass() provided by python. The method tells us if any classi a child of ane class Parent object) class chiar Parent) print(issubclass(chi2d, Parent) aTeue print(Ssaubelase(Parent, chile) afalse ‘+ We can check ifan object isan instance ofa class by making use of isinstanee() method! obja = chater) sa = Parent() print(isinstance(obj2, child)) False print(Ssinstance(obj2, Parent) sTrve Python Pandas Interview Questions 50. What do you know about pandas? «+ Pandas isan open-source, python-based library used in data manipulation applications requiring high performane {rom “Panel Data" having multidimensional data. This was developed in 2008 by Wes McKinney and was develope, + Pandas are useful in performing 5 major steps of data analysis - Load the data, clearv/manipulate it, prepare it, mot data 51. Define pandas dataframe. ‘A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columes. The syntax for creating dataframe: Anport pandes a8 pd atafrane ~ pé.DataFrane( datz, index, colunns, étype) data - Represents various forms lke series, map, ndarray, sts, dct etc index - Optional argument that represents an index to row labels. columns - Optional argument for column labels Supercharge your tech prype - the data type of each column, Again optional career! Atere the How will you combine different pandas dataframes? FREE live class dataframes can be combines using the below approaches: ok Now append() method This is used to stack the dataframes horizontally. Syntax Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 18135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) 42. 2ppenaer2) ‘+ concat) method: This is used to stack dataframes vertically. This is best used when the dataframes have the same fields. Syntax psconcot( (aft, 21) ++ Join method: Ths is used for extracting data from various dataframes having one oF more common columns. #2. jounter2) 53. Can you create a series from the dictionary object in pandas? Cone dimensional aray capable of storing different datatypes is called a series. We can create pandas series fiom a die below: Anport pandas 25 pe ket info = (*hayi" + 2.0, *hey2" = 2.2, “hey3" 2 2.2) series_obj = pa.sertes(aict_ info print (serses_obj) yoo3a type: floats Ian indexis not specified inthe input method, then the keys of the dictionaries ate sorted in ascending order for cons case the index i passed, then values ofthe index label wil be extracted from the dictionary. 54, How will you identify and deal with missing values in a dataframe? We can identify if dataframe has missing values by using the isnull) and isnad methods. nissing data, count-df,ssmul2().sun() \We can handle missing values by either replacing the values inthe column with 0 25 follows F{“cotunn none’) -F£2200(0) Cry replacing it with the mean value of the column 4F{‘colunn mane’ ] = of{‘colunn_nane | fi1Ina( (eff ‘eotuar_nane?].nean())) 55, What do you understand by reindexing in pandas? Reindexing isthe process of conforming 3 dataframe toa new index with optional filing loge. f the values are missing then NaN/NA is placed in the locaton, A new object is returned unless 2 new index is produced that is equivalent to th value is set to False, This is also used for changing the index of rows and columns in the dataframe, 56. How to add new column to pandas dataframe? ‘Anew column can be added to 8 pandas dataframe a follows: inport pandas 98 pa fate_info = (*flrst’ : pd.sertes((2, 2, 3], Andex{'a', "b', te") second” + pa.Serses((2, 2, 3, 4], indexe('a', "b', fe, "$092 = ps.dataFane(datinfo) “third” Jepa.sertes( 20, 20,38],tndexe"2","b","€°) ne (60) fourth’ Joar{ First’ J+infof "thine" nt (08) ‘Supercharge your tech career! Atterc the How will you delete indices, rows and columns from a dataframe? FREE live class slete an Index: Fencita. a) Ae tny name frramenina the inde bu name Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 19135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) 1 Alternatively, the af tnaex.nane can be assigned to None, ‘+ For example if you have the below dataframe: + To drop the index name “Names' printtar) To delete row/column from dataframe: ‘+ arop()_ method is used to delete row/column from dataframe. ‘+ The axis argument is passed to the drop method where ifthe value is 0 it indicates to drop/delete a row and if 1 column ‘+ Additionally, we can try to delete the rows/columns in place by setting the value of inplace to True. Ths makes sur Without the need for reassignment “+The duplicate values from the rowcolumn can be deleted by using the drop_duplicates() method 58. Can you get items of series A that are not available in another series 8? his can be achieved by using the ~ {not/negation symbal) and isin() method as shown below. Anport pandas 2s pe GPa = passeries( (2, 4, 8, 18) 221) af2 = pa.sertes((B, 22, 18, 25, 26)) saraeera[naf.s5in(4"2)] nt ef2) output: types ints 59, 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 bath series, then taking the interse {getting items of union that are not therein the lit ofthe intersection, tion of both series. Then we fe The following code demonstrates this: a ort ponas a pd fort nutpy a5 np peseries((2s 4, 5, 8, 281) = peuseriest(8, 26, 13,38, 27) Infon = passertes(apantonse(eft, 472)) 4 unton of series Supercharge your tech —ntersect = pé.series(op.intersecss(et2, of2))_# intersection of series career! cu shrets « snl nton infoerse)) Atterc the vues FREE live class put: Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 20135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) eyper ants 60. While importing data from different sources, can the pandas library recognize dates? Yes, they can but with some bit of help. We need to add the parse. dates argument while we are reading data from the example where we read data from a CSV fl, we may encounter diferent date-time formats that are not readable by tt ‘ase, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below: Inport pandas 35 pe fron eatetine import aatetine atoparser = Tanbds date_val: datetine.strptine(dste val, ‘RY-neKa ‘i:40:%5") GF = pa.read_csv("sone_file.csv", parse catess("satetine colum'), cate parseradatesarser) Numpy Interview Questions 61. 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 i arrays. NumPy is shor for NUMerical PYthon, This is very famous forts highly optimized tools that result in high pero [N-Dimensiona aray processing feature that Is designed explicit to work on complex arrays. Due to its popularity anc and its flexibility to perform various operations like trigonometric operations, algebraic and statstical computations it in performing scientific computations and various broadcasting functions, The following image shows the applications 62. How are NumPy arrays advantageous over python lists? ‘+ The lst data structure of python is very highly efficient and is capable of performing various functions, But, they he when it comes to the computation of vectrized operations which deals with elementavise multiplication and add aso require the information regarding the type of every element which resus in overhead as type dispatching co! time any operation i performed om any element. This is where the NumPy arays come into the picture as al the lists are handled in NumPy arrays. + Additionally, 35 the size ofthe NumPy arrays increases, NumPy becomes around 30x times faster than the Python | Numpy arays are densely packed in the memory due to their homogenous nature, Ths ensures the memory free) 63, What are the steps to create 1D, 2D and 3D arrays? 1 1 array creati s st = [1.2.4] ne Llane = np. array(one_dtnensional, List) print(*2D array 3s : ",one_dinenstioral_err) ‘+ 2D array creation: Anport runpy a5 0p ‘_tinensions]_Iist=[(3,2,31,14,5,61] 2_éinensional_arr = np.array( two, éSnenstonal_ List) print("2D array is : ";tw_dinenstoral_arr) ‘+ 3D array creation: Anport runpy a5 np a)_Lste[ [22,3], [45,6], (7,8, 9])) x ‘ee_dinensional_are = rpvarray(three_cinensionsl_List) nt(-30 array $5.5 thr re) IND array creation: This can be achieved by giving the ncmin atribute. The below example demonstrates the cree ‘Supercharge your tech ort numpy as no career! Attere the FREE live class vray = npeacray( (2 2, 3, 4], nd int(ndarray) Ie("Dimensions of arrays", nenrray.néin) ) You are given a numpy array and a new column as inputs. How will you delete the secon¢ Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 21135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Exampl Given array: [13s 53 63) [72 32 22] [aa 84 s6)) New Column valves 1 Solution: rputkeray = np-arcay({{35,53,63],[72,32,22], (4,84, 56]1]) rnew_col = np.array(([20,38,48)]) arr = npedelete(sonplearray 5 3, axis = 2) arr = npeinsert(arr 4 i, newcol, axis = 4) print (are) 65. How will you efficiently load data from a text file? We can use the method runpy.losctxt() which can automatically rea the file's header and footer lines andthe con This method is highly efficient and even if this method feels less efficient, then the data should be represented in a mo a5 CSV ete. Various alternatives can be considered depending on the version of NumPy used. Following are the fle formats that are supported: «Text files: These files are generally vey slow, huge but portable and are human-readable ‘+ Raw binary Tis file does not have any metadata and is not portable. But they are fast. ‘Pickle: These are borderine slow and portable but depends on the NumPy versions ‘+ HOES: Ths is known as the High-Powered Kitchen Sink format which supports bth PyTables and hSpy format, ‘+ _npy: This is NumPy's mative binary data format which is extremely simple, efficient and portable 66. How will you read CSV data into an array in NumPy? his can be achieved by using the genfromtat) method by setting the delimiter as a comma. ron nunpy import genérontxt csvdata = genfrontet("sanple_fie.cs¥", detiniter=',") 67. How will you sort the array based on the Nth column? For example, consider an array ar. are = mpeareay(ll8, 3, 2) 13, 6 Sie is 4 ai) X 1s ty to sort the roms by the 2nd column so that we get “tah, 3.216 Supercharge yourtech 511 career! ‘an do this by using the sort) method in numpy as atterethe FREE live class ort nunpy as np mpearray((t8s 3, 2], so 1, 6 SIs Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 22135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) are = np.sort(are.view('38,8,38"), order=["42"), view -Ant) We can also perform sorting and that too inplace sorting by doing arp.vieu("6,46,48")-sort(order=[f2"), axis=@) 68. How will you find the nearest value in a given numpy array? We can use the argmind) method of numpy as shown below: def Find_pearest_value(arr, value): are = np.asarray(err) np.abs(arr = value)).argntn() vetorn are( de] fare = npwarray([ 28868, 0.62384, 8.6242, 0.0225, 26541, 0.5645, @,5740]) print (find nearest value(anr, value)) @ Prints 8.5685 69, How will you reverse the numpy array using one line of code? ns ean be done as shown inthe following reversed array = arr{:#-2] where arr = original given array, reverse. array isthe resultant after reversing all elements inthe input 70. How will you find the shape of any given NumPy array? We can use the shape attribute of the numpy aray te of the aay find the shape. It returns the shape of the array in terms of row € are_tue_din = np.acray(((%2"s2", 33", "48"), (95° 6", 77 "8" )1) srr_one_din = np.aeray((3.2,4,5,6]) print("2-0 Array shape: print(“2-0 Array shape: 1 ane_two_éin-shape) are_one_ein. shape) output: 2.0 array Shape: (2, 4) 42-0 array shape: (5,) Python Libraries Interview Questions 71. Differentiate between a package and a module in python. ‘The module isa single python fileA module can import other modules (other python files) as objects. Wheress a pack folder/crectory where diferent sub-packages and the modules reside. [python module is created by saving 2 fle with the extension of py . This fle will have classes and functions that ar as well as across modules, x. thon package is created by following the below steps: create directory and give 2 valid name that represents its operation Place modules of one kind in this sirectory Supercharge your tech ‘teste _Init_.py fle inthis ectory. This es python know the directory we created sa package, The conte) career! Attere the FREE live class be imported across different modules in other packages to reuse the functionality What are some of the most commonly used built-in modules in Python? ‘on modules are the files having python code which can be functions, variables or classes. These go by py extensio able builtin modules ave: Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 23135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) math +98 = random + datetime + JSON 73. What are lambda functions? Lambda functions are generally inline, anonymous functions represented by a single expression, They are used for crea ring runtime, They can accept any number of parameters, They are usually used where functions are required only fe can be used as ul_fune = Lambda way: ty préntnut_funct6, 4)) f output: 24 74, How can you generate random numbers? Python provides a module called random using which we can generate random numbers ‘+ We have to importa random module and call the randon()_method as shown below: ‘© The random) method generates float values lying between 0 and 1 randamly. print (rendon.rendon()) + To generate customised random numbers between specified ranges, we can use the randrange() method Syntax: randrange(beginning, end, step) For example: print (randon.randrange(5,288,2)) 75. Can you easily check if all characters in the given string is alphanumeric? his can be easily done by making use ofthe isalnum9 method that returns true in cast ing has only alohanume For Example - abdea323°.ssainun() #Output: True sayr81238" Ssntrun() sOutput: Fase Another way i to use match¢) method from the re (regex) module as shown print boot (re-nateh(“[A-za-20-8]+$°, abde2923°))) # Outputs True Drint{bool(re.natch("[A-za-70-9]+8, 'xy281238"))) # Output: False 76. What are the differences between pickling and unpickling? Pickling isthe conversion of python objects to binary form. Whereas, unpicting isthe conversion of binary form data t pickled objects are used for storing in disks or external memory locations. Unpickled objects ave used for getting the d ‘objects upon which processing can be done in python, X on provides a pickle module for achieving this. Pickling uses the pickle.duyp() method ta dump python obj king uses the pickle.toad() method to get back the data as python objects, ‘Supercharge your tech career! Attere the FREE live class Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 24038 1219/21, 48 AM “Top Python Interview Questions (2021) - Inerviewsit Python Pickle Module Pickle Peedumpd Unpiekt Sen padtelood serene 8 interviewsit 71. Define GIL. Gl stands for Global Interpreter Lock. This a mutex used for iting access to python abjects and ads in efective te avoiding deadlocks. GIL helps in achieving muttasking (and not paalel computing). Te following eiagram represent vo vo WO WO vo Thread 1 run run Thread 2 Thread 3 ~~ Release Acquire Release Acquire GIL GIL GIL GIL Based on the above diagram, there ave thee treads, Fist Thread acquires the GIL fist and stats the /O execution. W ae dane, thread 1 releases the acquited GL whichis then taken up by the second thread, The process repeats and the citfrent treads altemativly unt the threads have completed their execution, The threads not having the GL lock go and resumes execution only when it acquires the lock 78. Define PYTHONPATH. Iv is an environment variable used fr incorporating addtional directories uring the import of a module or a package. for checking if the imported packages or modules are available inthe existing directories, Not just that, the interpreter variable to identify which module needs to be loaded. 79. Define PIP. i ctands for Python Installer Package. As the name indicates, itis used for installing diferent python modules. tis a4 X iding » seamles interface for installing diferent python modules. It searcher over the internet forthe package an¢ Sing arectory without the need for any interaction with the user. The syntax for this "install ‘Supercharge your tech career! ‘Are there any tools for identifying bugs and performing static analysis in python? Attercthe there are tools like PyChecker and Pylin which are used as static analysis and ining tools respectively. PyChecker FREE live class hitpslwwizinterviewbit.comipython-ntervew-questions! ‘on source code fles and raises alerts for code issues and their complexity. Pylint checks for the module's coding st rent plugins to enable custom features to meet this requirement. 1G Got suggestions? We would lve ta hear your feedback, 25135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Interviewait ‘Shallow copy does the task of creating new objects storing references of orginal elements. This does not undergo copies of nested objects. Itust copies the reference details of nested obje ++ Deep copy creates an independent and new copy of an object and even copies all the nested objects ofthe origin, 82. What is main function in python? How do you invoke it? Inthe world of programming languages, the mains considered as an entry point of execution for 9 program. But in py the interpreter serially interprets the file lin-by-line, This means that python does nat provide main() function expli ‘mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function ant __ane__ property of python fle This __nane___vatiable is» special ulin variable that points tothe name of the can be done as shown below: def maint) print (HL Enterviewbit!") main) Python Programming Examples 83. Write python function which takes a variable number of arguments. ‘A funetion that takes variable arguments is called a function prototype. Syntax def function nane(2rg ist) For example: de fune(+ver) prints) fonet3) une(28,2,6) The * inthe function argument represents variable arguments inthe function, 84, WAP (Write a program) which takes a sequence of numbers and check if all numbers are You can do this by converting thelist to set by using set) method and comparing the length of this set with the length found equa, return Tue def check distinct data 2st) AF len(aata List) == len(set{date_List)) se print (check. rant check stinet([4,6,5.8])) _ aPrints True stinct((2,2,5,5,7,8])) aPeints False 85, Write a program for counting the number of every character of a given text file. The idea is to use collections and print module as shown belowe ith open("sanple file txt", n°) as cate ‘count_data = collections. counter(date,read().upper()) count_value = pprint.proraat(count_dsta) nt(count_vatue) Write a program to check and return the pairs of a given array A whose sum value is equi ‘Supercharge your tech can be done easily by using the phenomenon of hashing. We can use a hash map to check for the curent value of career! he value of (Nd, then there is our pai. Atere the FREE live class Print pates(arr, 8) ach set hash set = s0t() Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 26135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) - Interviewait val = weare(s SF (val dm hash.set): chock £F Nex fs there tn set, pr print(*Pains " + str(are{i}) +, " + str(val)) hash set-ade(are( 1) arr = [2,2 49, 3, 9) 4] print_pairs(arr, N) 87. Write a Program to add two integers >0 without using the plus operator. We can use bitwise operators to achieve this uns (rurs, nun) print(aed_nunst2, 26)) 88, Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants: axstyec By solving the equation, we get Bb OHS KM tenp = atr = bee sf ie 8: x= (cin = bro) / temp y= (ato = ate) / temp prinetstr(xd, str(y)) 89. 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 ta perform regex pattern comparison here def natch text(txt_data) pattern = "ab(4,8) Af re.search(pattern, txt_deta): asearch for pi else return(“Hateh rot found’) print (raven. text("abe")) [sprints Match not foune Drint(nateh text(“aabbbbbe")) prints Mateh foura 90. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format. We can again use the re modille to convert the date string as shown belove def transform date format (date) return re. subir’ (\éC4))=(N6(2,2))-(N6C299", "\ABM2VM, date input = "2021-08-01" ne eransforndate_fornat date) can also use the datetime module as shown below 19 datetine import datetine Supercharge your tech gate = datetine.strptine( "2021-08-62", “BY-Xa-td").steftine("Mé:kn:B¥") career! einen data) Attercthe FREEliveclass Write a Program to combine two different dictionaries. While combining, if you find the s | the values of these same keys. Output the new dictionary (G Got suggestions? We would love to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 27135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) fron collections snport counter a = (keys: 50, "key2': 200, “key3":200) 2 = (keys: 200, "key?" 100, "keyt! 380) ew dict = Counter(ds) + Counter(2) print (new act) 92, How will you access the dataset of a publicly shared spreadsheet in CSV format stored in https//decspython.org/3/We can use the StringlO module from the io module to read from the Google Drive link and pandas library using the obtained data source, snport pandas cs¥_Link = "https://does. google. con/spreadsheets/4 data source = stringlo.stringlo(reqvests.get(csv_Link) cont fatafrane ~ pd.read_csv( datasource) print{éatafrane.hesd()) Conclusion In this article, we have seen commonly asked interview questions for a python developer. These questions along with » sessions will help you erack any python based interviews, Over the years, python has gained 3 lot of popularity among: community due to its simplicity and ability to support powerful computations. Due to this, the demand for geod pytho ‘growing, Nevertheless, to mention, the perks of being a python developer are really good, Along with theoretical know is an emphasis on the ability lo write good quality code as well. So, keep learning and keep practising problems and wi crack any interviews Important Resources: Python Basic Programs Python Projects Difference Between Python 2 and 3 Python Frameworks Python Documentation Numpy Tutorial Python Vs R Python Vs Javascript Difference Between C and Python Python Vs Java Features of Python GGolang vs Python Python Developer Skil Python MCQ x 1PP0se Kit? = (3445,2.1.0), what sist after st. pop th? Ist = Bas2m) Superchargeyour tech iT = BAs2a1 career! vat = 85210) atterethe . FREE live class vats = 1452) Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 28035 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) Hallo Wort © "Wola Heller © “atrow ote ° ll oro 3, What is the difference between fists and tuples? © Ustis» sequence data ype, while tuples not © Tuples are mutable but ts are immutable Tupleisa sequence data ype, while ssi not. (© Uist are mutable bu tuples are immtble A.Let func = 1anbda 2, b+ (2° b) , what isthe output of fune(sleat(se),20) 7 © rw00eeeeecoo00aee0000 © ter20 (© r00000dda00000000000.0 © 1oe+20 5. Which statement false forint? © ints called manual on object eeaton _ini_isa contactor method ineython © Aclasses have s_it_method associated with them. © —intatoeates memory for abject. 6. Which of the following isthe function responsible fr pickling? © pekesaveg © pieklesoreo © picketed © pickledumpo 7. Which ofthe following isa protected attribute? x = ‘Supercharge your tech career! seh Atere the FREE liveclass hich ofthe following is untrue for Python namespaces? okNow Python namespaces are implemented asa detonaey in Python Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-intervew-questions! 20135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) © Python namespaces have key a adestes ofthe objects © Lfecjle af namespace depends upon the scope ofthe objects they te Namespaces ensure that object names in program are unique Blet tists = [ies ory rip(uists, Listz)} ? pos] and List? = ['a", '3', 'n', ‘7 shat isthe output of [->-gosa(L4, 3] © evsvraysiins a a tees aya a © basse, an, 3h © tas 28 49h 18 1 aah 8a) 10. tine.tinet) in Python tetums? © Gatti © Current tine in milseconds ° Current tine in milizeconds since might anuary 1, 1970 © current ime in iliseconds since michight,anvary 1, 1970 GMT (the Unie) 11, What is the output ofthe following program? class A(object) ef init__(self, 3) ef mul_t00(se16) class 9(8) ef Linit_(sett, 9) X_anit_(self, 2) ef mul_thres(sel*) selF.nun "= 3 ony = 5¢0) print obj.) bg.ut_s40() prin (0b3.non) obj.mul_three() prine(ob3.nun) © 4024 4468 x 186 None of the above Supercharge your tech Yhatisthe output of the below program? career! oss tman(ob ec) Attene the def _Ankt_(self, nane) FREE live class Selfhuman_name = name — ‘def gettumanNane(sel*): Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 30135 1219/21, 9:46, AM ‘Top Python Interview Questions (2021) ef Astmployee( sel) return False lass Employee (inn) ef init__(self, sane, en9_19) Tuper(HeEnployes, se1¢).__inkt_(oane) ef istmpoyee( sel?) (ef get_enp_id( sel) nployee = T8Enployee "he Employee", *18007") princ(enployee.gertumanNane(), exployee.1sEnployee(), enployee.get_enp_sd() tNone, toe, 18007) © eMrEmployes Tue "8007 Fats, 18007) © Runtime eror 13, Which among the below options will correct the below error obtained wile reading “sample fle.csv" in pandas? Traceback (ost recent call last): File " unicodetncodes © pavead es'sample fev, encosing=t-8) © paread.csusample.fle es’ compresion= zip} © None of the above 14, Which among the following options helps us to check whether a pandas dataframe is empty? O- stamprytame otoank © dtisempy © temps 15, How will ou find the location of numbers which are muliples of Sin a series? import pandas 25 pd Anport sungy as np series_cata = pa.Sertes(np.randon.randint(1, 22, 7)) npsesrhseries dat %5) np fins cata % ‘Supercharge your tech i: career! np argwheretseries_< atterethe FREE live class nplocate(series_data % 5) ok Now ‘nat is the output ofthe below code? Got suggestions? We would lve to hear your feedback hitpslwwizinterviewbit.comipython-ntervew-questions! 31135, 1219/21, 9:46, AM class person def _inkt_(self, first_nane, last person = Parson(first first_sane = "LAN" person. 2ast_sane = "2QR" prin (person. firstname, person. last_nane) zac © yvzear © wn ase © vapor 17. Which among the below options picks out negative numbers from the given lst © tum forum inst) © rumen © num for sum in sit nom

You might also like