id
int64
0
25.6k
text
stringlengths
0
4.59k
3,300
let' look at second contrived example that illustrates this problem more clearly here we have base class that has method named call_me two subclasses override that methodand then another subclass extends both of these using multiple inheritance this is called diamond inheritance because of the diamond shape of the clas...
3,301
num_sub_calls def call_me(self)leftsubclass call_me(selfrightsubclass call_me(selfprint("calling method on subclass"self num_sub_calls + this example simply ensures that each overridden call_me method directly calls the parent method with the same name it lets us know each time method is called by printing the informat...
3,302
print("calling method on base class"self num_base_calls + class leftsubclass(baseclass)num_left_calls def call_me(self)super(call_me(print("calling method on left subclass"self num_left_calls + class rightsubclass(baseclass)num_right_calls def call_me(self)super(call_me(print("calling method on right subclass"self num_...
3,303
firstcall_me of subclass calls super(call_me()which happens to refer to leftsubclass call_me(the leftsubclass call_me(method then calls super(call_me()but in this casesuper(is referring to rightsubclass call_ me(pay particular attention to thisthe super call is not calling the method on the superclass of leftsubclass (...
3,304
python' function parameter syntax provides all the tools we need to do thisbut it makes the overall code look cumbersome have look at the proper version of the friend multiple inheritance codeclass contactall_contacts [def __init__(selfname=''email=''**kwargs)super(__init__(**kwargsself name name self email email self ...
3,305
the previous example does what it is supposed to do but it' starting to look messyand it has become difficult to answer the questionwhat arguments do we need to pass into friend __init__this is the foremost question for anyone planning to use the classso docstring should be added to the method to explain what is happen...
3,306
polymorphism we were introduced to polymorphism in object-oriented design it is fancy name describing simple conceptdifferent behaviors happen depending on which subclass is being usedwithout having to explicitly know what the subclass actually is as an exampleimagine program that plays audio files media player might n...
3,307
print("playing {as wavformat(self filename)class oggfile(audiofile)ext "oggdef play(self)print("playing {as oggformat(self filename)all audio files check to ensure that valid extension was given upon initialization but did you notice how the __init__ method in the parent class is able to access the ext class variable f...
3,308
polymorphism is actually one of the coolest things about object-oriented programmingand it makes some programming designs obvious that weren' possible in earlier paradigms howeverpython makes polymorphism less cool because of duck typing duck typing in python allows us to use any object that provides the required behav...
3,309
abstract base classes while duck typing is usefulit is not always easy to tell in advance if class is going to fulfill the protocol you require thereforepython introduced the idea of abstract base classes abstract base classesor abcsdefine set of methods and properties that class must implement in order to be considere...
3,310
nowwe can instantiate an oddcontainer object and determine thateven though we did not extend containerthe class is container objectfrom collections import container odd_container oddcontainer(isinstance(odd_containercontainertrue issubclass(oddcontainercontainertrue and that is why duck typing is way more awesome than ...
3,311
pass @classmethod def __subclasshook__(clsc)if cls is medialoaderattrs set(dir( )if set(cls __abstractmethods__<attrsreturn true return notimplemented this is complicated example that includes several python features that won' be explained until later in this book it is included here for completenessbut you don' need t...
3,312
since the wav class fails to implement the abstract attributesit is not possible to instantiate that class the class is still legal abstract classbut you' have to subclass it to actually do anything the ogg class supplies both attributesso it instantiates cleanly going back to the medialoader abclet' dissect that __sub...
3,313
all this line does is get the set of methods and properties that the class hasincluding any parent classes in its class hierarchyif set(cls __abstractmethods__<attrsthis line uses set notation to see whether the set of abstract methods in this class have been supplied in the candidate class note that it doesn' check to...
3,314
the project will allow the agent to interact with the objects using the python interpreter prompt in this world of graphical user interfaces and web applicationsyou might be wondering why we're creating such old-fashioned looking programs simply putboth windowed programs and web applications require lot of overhead kno...
3,315
finallywe'll need an agent object that holds list of all propertiesdisplays those propertiesand allows us to create new ones creating properties will entail prompting the user for the relevant details for each property type this could be done in the agent objectbut then agent would need to know lot of information about...
3,316
wowthat' lot of inheritance arrowsi don' think it would be possible to add another level of inheritance without crossing arrows multiple inheritance is messy businesseven at the design stage the trickiest aspects of these classes is going to be ensuring superclass methods get called in the inheritance hierarchy let' st...
3,317
the apartment class extends propertyand is similar in structureclass apartment(property)valid_laundries ("coin""ensuite""none"valid_balconies ("yes""no""solarium"def __init__(selfbalcony=''laundry=''**kwargs)super(__init__(**kwargsself balcony balcony self laundry laundry def display(self)super(display(print("apartment...
3,318
the prompt_init static method is now getting dictionary values from the parent classand then adding some additional values of its own it calls the dict update method to merge the new dictionary values into the first one howeverthat prompt_init method is looking pretty uglyit loops twice until the user enters valid inpu...
3,319
"what laundry facilities does "the property have"apartment valid_laundriesbalcony get_valid_input"does the property have balcony"apartment valid_balconiesparent_init update("laundry"laundry"balcony"balcony }return parent_init prompt_init staticmethod(prompt_initthat' much easier to read (and maintain!than our original ...
3,320
num_stories input("how many stories"parent_init update("fenced"fenced"garage"garage"num_stories"num_stories }return parent_init prompt_init staticmethod(prompt_initthere' nothing new to explore hereso let' move on to the purchase and rental classes in spite of having apparently different purposesthey are also similar i...
3,321
print("rent{}format(self rent)print("estimated utilities{}formatself utilities)print("furnished{}format(self furnished)def prompt_init()return dictrent=input("what is the monthly rent")utilities=input"what are the estimated utilities")furnished get_valid_input"is the property furnished"("yes""no"))prompt_init staticmet...
3,322
is the property furnished(yesnono house houserental(**inithouse display(property details ===============square footage bedrooms bathrooms house details of stories garagenone fenced yardno rental details rent estimated utilities furnishedno it looks like it is working fine the prompt_init method is prompting for initial...
3,323
now that we have tested itwe are prepared to create the rest of our combined subclassesclass apartmentrental(rentalapartment)def prompt_init()init apartment prompt_init(init update(rental prompt_init()return init prompt_init staticmethod(prompt_initclass apartmentpurchase(purchaseapartment)def prompt_init()init apartme...
3,324
("apartment""rental")apartmentrental("apartment""purchase")apartmentpurchase that' some pretty funny looking code this is dictionarywhere the keys are tuples of two distinct stringsand the values are class objects class objectsyesclasses can be passed aroundrenamedand stored in containers just like normal objects or pr...
3,325
is the yard fenced(yesnoyes is there garage(attacheddetachednonedetached how many stories what is the monthly rent what are the estimated utilitiesincluded is the property furnished(yesnono agent add_property(what type of propertywhat payment type(houseapartmentapartment (purchaserentalpurchase enter the square feet en...
3,326
bathrooms apartment details laundryensuite has balconyyes purchase details selling price$ , estimated taxes exercises look around you at some of the physical objects in your workspace and see if you can describe them in an inheritance hierarchy humans have been dividing the world into taxonomies like this for centuries...
3,327
finallytry adding some new features to the three designs whatever features strike your fancy are fine ' like to see way to differentiate between available and unavailable propertiesfor starters it' not of much use to me if it' already rentedwhich design is easiest to extendwhich is hardestif somebody asked you why you ...
3,328
programs are very fragile it would be ideal if code always returned valid resultbut sometimes valid result can' be calculated for exampleit' not possible to divide by zeroor to access the eighth item in five-item list in the old daysthe only way around this was to rigorously check the inputs for every function to make ...
3,329
raising exceptions in principlean exception is just an object there are many different exception classes availableand we can easily define more of our own the one thing they all have in common is that they inherit from built-in class called baseexception these exception objects become special when they are handled insi...
3,330
file ""line in typeerrorcan only concatenate list (not "int"to list lst add traceback (most recent call last)file ""line in attributeerror'listobject has no attribute 'addd {' ''hello' [' 'traceback (most recent call last)file ""line in keyerror'bprint(this_is_not_a_vartraceback (most recent call last)file ""line in na...
3,331
class evenonly(list)def append(selfinteger)if not isinstance(integerint)raise typeerror("only integers can be added"if integer raise valueerror("only even numbers can be added"super(append(integerthis class extends the list built-inas we discussed in objects in pythonand overrides the append method to check two conditi...
3,332
while this class is effective for demonstrating exceptions in actionit isn' very good at its job it is still possible to get other values into the list using index notation or slice notation this can all be avoided by overriding other appropriate methodssome of which are double-underscore methods the effects of an exce...
3,333
when we call this functionwe see that the first print statement executesas well as the first line in the no_return function but once the exception is raisednothing else executescall_exceptor(call_exceptor starts here am about to raise an exception traceback (most recent call last)file ""line in file "method_calls_excep...
3,334
if we run this simple script using our existing no_return functionwhich as we know very wellalways throws an exceptionwe get this outputi am about to raise an exception caught an exception executed after the exception the no_return function happily informs us that it is about to raise an exceptionbut we fooled it and c...
3,335
the first line of output shows that if we enter we get properly mocked if we call with valid number (note that it' not an integerbut it' still valid divisor)it operates correctly yet if we enter string (you were wondering how to get typeerrorweren' you?)it fails with an exception if we had used an empty except clause t...
3,336
the number and the string are both caught by the except clauseand suitable error message is printed the exception from the number is not caught because it is valueerrorwhich was not included in the types of exceptions being handled this is all well and goodbut what if we want to catch different exceptions and do differ...
3,337
sometimeswhen we catch an exceptionwe need reference to the exception object itself this most often happens when we define our own exceptions with custom argumentsbut can also be relevant with standard exceptions most exception classes accept set of arguments in their constructorand we might want to access those attrib...
3,338
if we run this example--which illustrates almost every conceivable exception handling scenario-- few timeswe'll get different output each timedepending on which exception random chooses here are some example runspython finally_and_else py raising none this code called if there is no exception this cleanup code is alway...
3,339
alsopay attention to the output when no exception is raisedboth the else and the finally clauses are executed the else clause may seem redundantas the code that should be executed only when no exception is raised could just be placed after the entire try except block the difference is that the else block will still be ...
3,340
here is class diagram that fully illustrates the exception hierarchysystemexit baseexception keyboardinterrupt exception most other exception when we use the exceptclause without specifying any type of exceptionit will catch all subclasses of baseexceptionwhich is to sayit will catch all exceptionsincluding the two spe...
3,341
of courseif we do want to customize the initializerwe are free to do so here' an exception whose initializer accepts the current balance and the amount the user wanted to withdraw in additionit adds method to calculate how overdrawn the request wasclass invalidwithdrawal(exception)def __init__(selfbalanceamount)super(_...
3,342
exceptions aren' exceptional novice programmers tend to think of exceptions as only useful for exceptional circumstances howeverthe definition of exceptional circumstances can be vague and subject to interpretation consider the following two functionsdef divide_with_exception(numberdivisor)tryprint("{{{}formatnumberdiv...
3,343
python programmers tend to follow model of ask forgiveness rather than permissionwhich is to saythey execute code and then deal with anything that goes wrong the alternativeto look before you leapis generally frowned upon there are few reasons for thisbut the main one is that it shouldn' be necessary to burn cpu cycles...
3,344
'''if the item is not lockedraise an exception if the item_type does not existraise an exception if the item is currently out of stockraise an exception if the item is availablesubtract one item and return the number of items left ''pass we could hand this object prototype to developer and have them implement the metho...
3,345
using exceptions for flow control can make for some handy program designs the important thing to take from this discussion is that exceptions are not bad thing that we should try to avoid having an exception occur does not mean that you should have prevented this exceptional circumstance from happening ratherit is just...
3,346
there' simple analysisnow let' proceed with design we're obviously going to need user class that stores the username and an encrypted password this class will also allow user to log in by checking whether supplied password is valid we probably won' need permission classas those can just be strings mapped to list of use...
3,347
since the code for encrypting password is required in both __init__ and check_ passwordwe pull it out to its own method this wayit only needs to be changed in one place if someone realizes it is insecure and needs improvement this class could easily be extended to include mandatory or optional personal detailssuch as n...
3,348
users logging in and out ''self users {def add_user(selfusernamepassword)if username in self usersraise usernamealreadyexists(usernameif len(password raise passwordtooshort(usernameself users[usernameuser(usernamepasswordwe couldof courseextend the password validation to raise exceptions for passwords that are too easy...
3,349
we can also add method to check whether particular username is logged in deciding whether to use an exception here is trickier should we raise an exception if the username does not existshould we raise an exception if the user is not logged into answer these questionswe need to think about how the method would be acces...
3,350
raise permissionerror("permission exists"def permit_user(selfperm_nameusername)'''grant the given permission to the user''tryperm_set self permissions[perm_nameexcept keyerrorraise permissionerror("permission does not exist"elseif username not in self authenticator usersraise invalidusername(usernameperm_set add(userna...
3,351
there are two new exceptions in herethey both take usernamesso we'll define them as subclasses of authexceptionclass notloggedinerror(authexception)pass class notpermittederror(authexception)pass finallywe can add default authorizor to go with our default authenticatorauthorizor authorizor(authenticatorthat completes b...
3,352
keyerror'mixduring handling of the above exceptionanother exception occurredtraceback (most recent call last)file ""line in file "auth py"line in check_permission raise permissionerror("permission does not exist"auth permissionerrorpermission does not exist auth authorizor permit_user("mix""joe"traceback (most recent c...
3,353
def __init__(self)self username none self menu_map "login"self login"test"self test"change"self change"quit"self quit def login(self)logged_in false while not logged_inusername input("username"password input("password"trylogged_in auth authenticator loginusernamepasswordexcept auth invalidusernameprint("sorrythat usern...
3,354
raise systemexit(def menu(self)tryanswer "while trueprint(""please enter command\tlogin\tlogin \ttest\ttest the program \tchange\tchange the program \tquit\tquit """answer input("enter command"lower(tryfunc self menu_map[answerexcept keyerrorprint("{is not valid optionformatanswer)elsefunc(finallyprint("thank you for t...
3,355
some common places to look are file / (is it possible your code will try to read file that doesn' exist?)mathematical expressions (is it possible that value you are dividing by is zero?)list indices (is the list empty?)and dictionaries (does the key exist?ask yourself if you should ignore the problemhandle it by checki...
3,356
programming in previous we've covered many of the defining features of object-oriented programming we now know the principles and paradigms of object-oriented designand we've covered the syntax of object-oriented programming in python yetwe don' know exactly how and when to utilize these principles and syntax in practi...
3,357
identifying objects is very important task in object-oriented analysis and programming but it isn' always as easy as counting the nouns in short paragraphas we've been doing rememberobjects are things that have both data and behavior if we are working only with datawe are often better off storing it in listsetdictionar...
3,358
for the previous codemaybe yesmaybe no with our recent experience in object-oriented principleswe can write an object-oriented version in record time let' compare them import math class pointdef __init__(selfxy)self self def distance(selfp )return math sqrt((self - )** (self - )** class polygondef __init__(self)self ve...
3,359
that' fairly succinct and easy to readyou might thinkbut let' compare it to the function-based codesquare [( , )( , )( , )( , )perimeter(square hmmmaybe the object-oriented api isn' so compactthat saidi' argue that it was easier to read than the functional examplehow do we know what the list of tuples is supposed to re...
3,360
stillthere' no clear winner between the object-oriented and more data-oriented versions of this code they both do the same thing if we have new functions that accept polygon argumentsuch as area(polygonor point_in_polygon(polygonxy)the benefits of the object-oriented code become increasingly obvious likewiseif we add o...
3,361
before we get into the detailslet' discuss some bad object-oriented theory many object-oriented languages (java is the most notoriousteach us to never access attributes directly they insist that we write attribute access like thisclass colordef __init__(selfrgb_valuename)self _rgb_value rgb_value self _name name def se...
3,362
in codewe could decide to change the set_name(method as followsdef set_name(selfname)if not nameraise exception("invalid name"self _name name nowin java and similar languagesif we had written our original code to do direct attribute accessand then later changed it to method like the preceding onewe' have problemanyone ...
3,363
finallywe have the property declaration at the bottom this is the magic it creates new attribute on the color class called namewhich now replaces the previous name attribute it sets this attribute to be propertywhich calls the two methods we just created whenever the property is accessed or changed this new version of ...
3,364
this property constructor can actually accept two additional argumentsa deletion function and docstring for the property the delete function is rarely supplied in practicebut it can be useful for logging that value has been deletedor possibly to veto deleting if we have reason to do so the docstring is just string desc...
3,365
data descriptors defined here__dict__ dictionary for instance variables (if defined__weakref__ list of weak references to the object (if definedsilly this is silly property once againeverything is working as we planned in practiceproperties are normally only defined with the first two parametersthe getter and setter fu...
3,366
going one step furtherwe can specify setter function for the new property as followsclass foo@property def foo(self)return self _foo @foo setter def foo(selfvalue)self _foo value this syntax looks pretty oddalthough the intent is obvious firstwe decorate the foo method as getter thenwe decorate second method with exact...
3,367
deciding when to use properties with the property built-in clouding the division between behavior and datait can be confusing to know which one to choose the example use case we saw earlier is one of the most common uses of propertieswe have some data on class that we later want to add behavior to there are also other ...
3,368
def content(self)if not self _contentprint("retrieving new page "self _content urlopen(self urlread(return self _content we can test this code to see that the page is only retrieved onceimport time webpage webpage(now time time(content webpage content retrieving new page time time(now now time time(content webpage cont...
3,369
of coursewe could have made this method insteadbut then we should call it calculate_average()since methods represent actions but property called average is more suitableboth easier to typeand easier to read custom setters are useful for validationas we've already seenbut they can also be used to proxy value to another ...
3,370
from pathlib import path class zipreplacedef __init__(selffilenamesearch_stringreplace_string)self filename filename self search_string search_string self replace_string replace_string self temp_directory path("unzipped-{}formatfilename)thenwe create an overall "managermethod for each of the three steps this method del...
3,371
with filename open(" "as filefile write(contentsdef zip_files(self)with zipfile zipfile(self filename' 'as filefor filename in self temp_directory iterdir()file write(str(filename)filename nameshutil rmtree(str(self temp_directory)if __name__ ="__main__"zipreplace(*sys argv[ : ]zip_find_replace(for brevitythe code for ...
3,372
there are several reasonsbut they all boil down to readability and maintainability when we're writing new piece of code that is similar to an earlier piecethe easiest thing to do is copy the old code and change whatever needs to be changed (variable nameslogiccommentsto make it work in the new location alternativelyif ...
3,373
this is why programmersespecially python programmers (who tend to value elegant code more than average)follow what is known as the don' repeat yourself (dryprinciple dry code is maintainable code my advice to beginning programmers is to never use the copy and paste feature of their editor to intermediate programmersi s...
3,374
self temp_directory path("unzipped-{}formatzipname[:- ])def process_zip(self)self unzip_files(self process_files(self zip_files(def unzip_files(self)self temp_directory mkdir(with zipfile zipfile(self zipnameas zipzip extractall(str(self temp_directory)def zip_files(self)with zipfile zipfile(self zipname' 'as filefor f...
3,375
self search_string search_string self replace_string replace_string def process_files(self)'''perform search and replace on all files in the temporary directory''for filename in self temp_directory iterdir()with filename open(as filecontents file read(contents contents replaceself search_stringself replace_stringwith f...
3,376
scaled im resize(( )scaled save(str(filename)if __name__ ="__main__"scalezip(*sys argv[ : ]process_zip(look how simple this class isall that work we did earlier paid off all we do is open each file (assuming that it is an imageit will unceremoniously crash if file cannot be opened)scale itand save it back the zipproces...
3,377
we'll answer these questions as we gobut let' start with the simplest possible document class first and see what it can doclass documentdef __init__(self)self characters [self cursor self filename 'def insert(selfcharacter)self characters insert(self cursorcharacterself cursor + def delete(self)del self characters[self...
3,378
looks like it' working we could connect keyboard' letter and arrow keys to these methods and the document would track everything just fine but what if we want to connect more than just arrow keys what if we want to connect the home and end keys as wellwe could add more methods to the document class that search forward ...
3,379
this code is not very safe you can very easily move past the ending positionand if you try to go home on an empty fileit will crash these examples are kept short to make them readablebut that doesn' mean they are defensiveyou can improve the error checking of this code as an exerciseit might be great opportunity to exp...
3,380
insert(' ' insert(' ' insert(' ' insert(' ' cursor home( insert("*"print("join( characters)hello *world nowsince we've been using that string join function lot (to concatenate the characters so we can see the actual document contents)we can add property to the document class to give us the complete string@property def ...
3,381
wellclearlywe might want to do things with characterssuch as delete or copy thembut those are things that need to be handled at the document levelsince they are really modifying the list of characters are there things that need to be done to individual charactersactuallynow that we're thinking about what character clas...
3,382
this class allows us to create characters and prefix them with special character when the str(function is applied to them nothing too exciting there we only have to make few minor modifications to the document and cursor classes to work with this class in the document classwe add these two lines at the beginning of the...
3,383
got to beginning of file before newline break def end(self)while self position lenself document charactersand self document charactersself position character !'\ 'self position + this completes the formatting of characters we can test it to see that it worksd document( insert(' ' insert(' ' insert(character(' 'bold=tru...
3,384
as expectedwhenever we print the stringeach bold character is preceded by charactereach italic character by characterand each underlined character by character all our functions seem to workand we can modify characters in the list after the fact we have working rich text document object that could be plugged into prope...
3,385
which version do you find easier to usewhich is more elegantwhat is easier to readthese are subjective questionsthe answer varies for each of us knowing the answerhoweveris importantif you find you prefer inheritance over compositionyou have to pay attention that you don' overuse inheritance in your daily coding if you...
3,386
in our examples so farwe've already seen many of the built-in python data structures in action you've probably also covered many of them in introductory books or tutorials in this we'll be discussing the object-oriented features of these data structureswhen they should be used instead of regular classand when they shou...
3,387
unfortunatelyas you can seeit' not possible to set any attributes on an object that was instantiated directly this isn' because the python developers wanted to force us to write our own classesor anything so sinister they did this to save memorya lot of memory when python allows an object to have arbitrary attributesit...
3,388
tuples and named tuples tuples are objects that can store specific number of other objects in order they are immutableso we can' addremoveor replace objects on the fly this may seem like massive restrictionbut the truth isif you need to modify tupleyou're using the wrong data type (usually list would be more suitableth...
3,389
this example also illustrates tuple unpacking the first line inside the function unpacks the stock parameter into four different variables the tuple has to be exactly the same length as the number of variablesor it will raise an exception we can also see an example of tuple unpacking on the last linewhere the tuple ret...
3,390
named tuples sowhat do we do when we want to group values togetherbut know we're frequently going to need to access them individuallywellwe could use an empty objectas discussed in the previous section (but that is rarely useful unless we anticipate adding behavior later)or we could use dictionary (most useful if we do...
3,391
named tuples are perfect for many "data onlyrepresentationsbut they are not ideal for all situations like tuples and stringsnamed tuples are immutableso we cannot modify an attribute once it has been set for examplethe current value of my company' stock has gone down since we started this discussionbut we can' set the ...
3,392
as we've seen in previous exampleswe can then look up values in the dictionary by requesting key inside square brackets if the key is not in the dictionaryit will raise an exceptionstocks["goog"( stocks["rim"traceback (most recent call last)file ""line in keyerror'rimwe canof coursecatch the keyerror and handle it but ...
3,393
the goog stock was already in the dictionaryso when we tried to setdefault it to an invalid valueit just returned the value already in the dictionary bbry was not in the dictionaryso setdefault returned the default value and set the new value in the dictionary for us we then check that the new stock isindeedin the dict...
3,394
we've been using strings as dictionary keysso farbut we aren' limited to string keys it is common to use strings as keysespecially when we're storing data in dictionary to gather it together (instead of using an object with named propertiesbut we can also use tuplesnumbersor even objects we've defined ourselves as dict...
3,395
in contrastthere are no limits on the types of objects that can be used as dictionary values we can use string key that maps to list valuefor exampleor we can have nested dictionary as value in another dictionary dictionary use cases dictionaries are extremely versatile and have numerous uses there are two major ways t...
3,396
for letter in sentencefrequencies[letter+ return frequencies this code looks like it couldn' possibly work the defaultdict accepts function in its constructor whenever key is accessed that is not already in the dictionaryit calls that functionwith no parametersto create default value in this casethe function it calls i...
3,397
defaultdict({' '( ['hello'])' '( ['world'])}when we print dict at the endwe see that the counter really was working this examplewhile succinctly demonstrating how to create our own function for defaultdictis not actually very good codeusing global variable means that if we created four different defaultdict segments th...
3,398
"the children voted for {ice creamformatcounter(responsesmost_common( )[ ][ presumablyyou' get the responses from database or by using complicated vision algorithm to count the kids who raised their hands herewe hardcode it so that we can test the most_common method it returns list that has only one element (because we...
3,399
like dictionariespython lists use an extremely efficient and well-tuned internal data structure so we can worry about what we're storingrather than how we're storing it many object-oriented languages provide different data structures for queuesstackslinked listsand array-based lists python does provide special instance...