id
int64
0
25.6k
text
stringlengths
0
4.59k
800
is formally described as follows (brackets denote optional components and are not coded literally)[[fill]align][sign][#][ ][width][,]precision][typecodein thisfill can be any fill character other than or }align may be =or ^for left alignmentright alignmentpadding after sign characteror centered alignmentrespectivelysign may be +-or spaceand the (commaoption requests comma for thousands separator as of python and width and precision are much as in the expressionand the formatspec may also contain nested {format strings with field names onlyto take values from the arguments list dynamically (much like the in formatting expressionsthe method' typecode options almost completely overlap with those used in expressions and listed previously in table - but the format method also allows type code used to display integers in binary format (it' equivalent to using the bin built-in call)allows type code to display percentagesand uses only for base- integers ( or are not used herenote that unlike the expression' %sthe type code here requires string object argumentomit the type code to accept any type generically see python' library manual for more on substitution syntax that we'll omit here in addition to the string' format methoda single object may also be formatted with the format(objectformatspecbuilt-in function (which the method uses internally)and may be customized in user-defined classes with the __format__ operator-overloading method (see part viadvanced formatting method examples as you can tellthe syntax can be complex in formatting methods because your best ally in such cases is often the interactive prompt herelet' turn to some examples in the following{ : means the first positional argument in field characters wide{ :< means the second positional argument left-justified in -character-wide fieldand { platform:> means the platform attribute of the first argument rightjustified in -character-wide field (note again the use of dict(to make dictionary from keyword argumentscovered in and )'{ : { : }format('spam' 'spam in python '{ :> { :< }format('spam' spam '{ platform:> { [kind]:< }format(sysdict(kind='laptop')win laptop in all casesyou can omit the argument number as of python and if you're selecting them from left to right with relative autonumbering--though this makes your string formatting method calls
801
method over the formatting expression (see the related note ahead)'{: {: }format('spam' 'spam '{:> {:< }format('spam' spam 'platform:> {[kind]:< }format(sysdict(kind='laptop')win laptop floating-point numbers support the same type codes and formatting specificity in formatting method calls as in expressions for instancein the following { :gmeans the third argument formatted by default according to the "gfloating-point representation{ fdesignates the "ffloating-point format with just two decimal digitsand { : fadds field with width of six characters and zero padding on the left'{ : }{ }{ : }format( ' + + '{ : }{ }{ : }format( ' hexoctaland binary formats are supported by the format method as well in factstring formatting is an alternative to some of the built-in functions that format integers to given base'{ : }{ : }{ : }format( 'ff hexoctalbinary bin( )int(' ' ) (' ' other to/from binary hex( )int('ff' ) xff (' xff' other to/from hex oct( )int(' ' ) (' ' other to/from octalin prints and accepts formatting parameters can either be hardcoded in format strings or taken from the arguments list dynamically by nested format syntaxmuch like the syntax in formatting expressionswidth and precision'{ }format( ' ' ( ' parameters hardcoded '{ { } }format( ' '* ( ' take value from arguments string fundamentals ditto for expression ditto for expression
802
be used to format single item it' more concise alternative to the string format methodand is roughly similar to formatting single item with the formatting expressionstring method '{ }format( ' format( '' ' ' built-in function expression technicallythe format built-in runs the subject object' __format__ methodwhich the str format method does internally for each formatted item it' still more verbose than the original expression' equivalent herethough--which leads us to the next section comparison to the formatting expression if you study the prior sections closelyyou'll probably notice that at least for positional references and dictionary keysthe string format method looks very much like the formatting expressionespecially in advanced use with type codes and extra formatting syntax in factin common use cases formatting expressions may be easier to code than formatting method callsespecially when you're using the generic % print-string substitution targetand even with autonumbering of fields added in and print('% =% ('spam' )format expressionin all / print('{ }={ }format('spam' )format methodin and print('{}={}format('spam' )with autonumberingin and as we'll see in momentmore complex formatting tends to be draw in terms of complexity (difficult tasks are generally difficultregardless of approach)and some see the formatting method as redundant given the pervasiveness of the expression on the other handthe formatting method also offers few potential advantages for examplethe original expression can' handle keywordsattribute referencesand binary type codesalthough dictionary key references in format strings can often achieve similar goals to see how the two techniques overlapcompare the following expressions to the equivalent format method calls shown earlier'% % and % ( [ ]' and [ ]arbitrary types 'my %(kind) runs %(platform) {'kind''laptop''platform'sys platform'my laptop runs win 'my %(kind) runs %(platform)sdict(kind='laptop'platform=sys platform'my laptop runs win somelist list('spam'string formatting method calls
803
'first=%slast=%smiddle=%sparts "first=slast=mmiddle=[' '' ']when more complex formatting is applied the two techniques approach parity in terms of complexityalthough if you compare the following with the format method call equivalents listed earlier you'll again find that the expressions tend to be bit simpler and more concisein python adding specific formatting '%- % ('spam' 'spam '% %- ('spam' spam '%(plat) %(kind)- sdict(plat=sys platformkind='laptop'win laptop floating-point numbers '% % ( ' + + '% % ( ' hex and octalbut not binary (see ahead'% % ( 'ff the format method has handful of advanced features that the expression does notbut even more involved formatting still seems to be essentially draw in terms of complexity for instancethe following shows the same result generated with both techniqueswith field sizes and justifications and various argument reference methodshardcoded references in both import sys 'my { [kind]: }format(sys{'kind''laptop'}'my laptop runs win 'my %(kind)- runs %(plat) sdict(kind='laptop'plat=sys platform'my laptop runs win in practiceprograms are less likely to hardcode references like this than to execute code that builds up set of substitution data ahead of time (for instanceto collect input form or database data to substitute into an html template all at oncewhen we account for common practice in examples like thisthe comparison between the format method and the expression is even more direct string fundamentals
804
data dict(platform=sys platformkind='laptop''my {kind: }format(**data'my laptop runs win 'my %(kind)- runs %(platform) sdata 'my laptop runs win as we'll see in the **data in the method call here is special syntax that unpacks dictionary of keys and values into individual "name=valuekeyword arguments so they can be referenced by name in the format string--another unavoidable far conceptual forward reference to function call toolswhich may be another downside of the format method in generalespecially for newcomers as usualthoughthe python community will have to decide whether expressionsformat method callsor toolset with both techniques proves better over time experiment with these techniques on your own to get feel for what they offerand be sure to see the library reference manuals for python and later for more details string format method enhancements in python and python and added thousand-separator syntax for numberswhich inserts commas between three-digit groups to make this workadd comma before the type codeand between the width and precision if presentas follows'{ : }format( ' '{ :, }format( ' , , , these pythons also assign relative numbers to substitution targets automatically if they are not included explicitlythough using this extension doesn' apply in all use casesand may negate one of the main benefits of the formatting method--its more explicit code'{:, }format( ' , , , '{:, {:, }format( ' , , , , '{: }format( ' , see the release notes for more details see also the formats py commainsertion and money-formatting function examples in for simple manual solution that can be imported and used prior to python and as typical in programmingit' straightforward to implement new functionality in callablereusableand customizable function of your ownrather than relying on fixed set of built-in toolsfrom formats import commasmoney '%scommas( ' , , , '% % (commas( )commas( )string formatting method calls
805
'%smoney( '$ , and as usuala simple function like this can be applied in more advanced contexts toosuch as the iteration tools we met in and will study fully in later [commas(xfor in ( )[' , , '' , , ''% %stuple(commas(xfor in ( )' , , , , 'join(commas(xfor in ( )' , , , , for better or worsepython developers often seem to prefer adding special-case built-in tools over general development techniques-- tradeoff explored in the next section why the format methodnow that 've gone to such lengths to compare and contrast the two formatting techniquesi wish to also explain why you still might want to consider using the format method variant at times in shortalthough the formatting method can sometimes require more codeit alsohas handful of extra features not found in the expression itself (though can use alternativeshas more flexible value reference syntax (though it may be overkilland often has equivalentscan make substitution value references more explicit (though this is now optionaltrades an operator for more mnemonic method name (though this is also more verbosedoes not allow different syntax for single and multiple values (though practice suggests this is trivialas function can be used in places an expression cannot (though one-line function renders this mootalthough both techniques are available today and the formatting expression is still widely usedthe format method might eventually grow in popularity and may receive more attention from python developers in the future furtherwith both the expression and method in the languageeither may appear in code you will encounter so it behooves you to understand both but because the choice is currently still yours to make in new codelet' briefly expand on the tradeoffs before closing the book on this topic extra featuresspecial-case "batteriesversus general techniques the method call supports few extras that the expression does notsuch as binary type codes and (as of python and thousands groupings as we've seenthoughthe string fundamentals
806
case for binary formatting'{ : }format(( * expression (onlybinary format code ' '% (( * valueerrorunsupported format character 'bbin(( * ' '%sbin(( * ' '{}format(bin(( * )' but other more general options work too '%sbin(( * )[ :' slice off to get exact equivalent usable with both method and expression with relative numbering the preceding note showed that general functions could similarly stand in for the format method' thousands groupings optionand more fully support customization in this casea simple -line reusable function buys us the same utility without extra specialcase syntax'{:, }format( ' , , , new str format method feature in '%scommas( ' , , , but is same with simple -line function see the prior note for more comma comparisons this is essentially the same as the preceding bin case for binary formattingbut the commas function here is user-definednot built in as suchthis technique is far more general purpose than precoded tools or special syntax added for single purpose this case also seems indicativeperhapsof trend in python (and scripting language in generaltoward relying more on special-case "batteries includedtools than on general development techniques-- mindset that makes code dependent on those batteriesand seems difficult to justify unless one views software development as an end-user enterprise to someprogrammers might be better served learning how to code an algorithm to insert commas than be provided tool that does we'll leave that philosophical debate aside herebut in practical terms the net effect of the trend in this case is extra syntax for you to have to both learn and remember given their alternativesit' not clear that these extra features of the methods by themselves are compelling enough to be decisive flexible reference syntaxextra complexity and functional overlap the method call also supports key and attribute references directlywhich some may see as more flexible but as we saw in earlier examples comparing dictionary-based formatting in the expression to key and attribute references in the format methodthe string formatting method calls
807
can reference the same value multiple times'{name{job{name}format(name='bob'job='dev''bob dev bob'%(name) %(job) %(name)sdict(name='bob'job='dev''bob dev bobespecially in common practicethoughthe expression seems just as simpleor simplerd dict(name='bob'job='dev''{ [name]{ [job]{ [name]}format( 'bob dev bob'{name{job{name}format(** 'bob dev bob'%(name) %(job) %(name)sd 'bob dev bobmethodkey references methoddict-to-args expressionkey references to be fairthe method has even more specialized substitution syntaxand other comparisons might favor either scheme in small ways but given the overlap and extra complexityone could argue that the format method' utility seems either washor features in search of use cases at the leastthe added conceptual burden on python programmers who may now need to know both tools doesn' seem clearly justified explicit value referencesnow optional and unlikely to be used one use case where the format method is at least debatably clearer is when there are many values to be substituted into the format string the lister py classes example we'll meet in for examplesubstitutes six items into single stringand in this case the method' {iposition labels seem marginally easier to read than the expression' % '\ % \nexpression '\ { }\nformatmethod on the other handusing dictionary keys in expressions can mitigate much of this difference this is also something of worst-case scenario for formatting complexityand not very common in practicemore typical use cases seem more of tossup furtheras of python and numbering substitution targets becomes optional when relative to positionpotentially subverting this purported benefit altogether'the { side { { }format('bright''of''life''the bright side of lifepython 'the {side {{}format('bright''of''life''the bright side of lifepython + 'the % side % % ('bright''of''life''the bright side of lifeall pythons given its concisenessthe second of these is likely to be preferred to the firstbut seems to negate part of the method' advantage compare the effect on floating-point for string fundamentals
808
less cluttered'{ : }{ }{ : }format( ' '{: }{ }{: }format( ' '% % ( ' named method and context-neutral argumentsaesthetics versus practice the formatting method also claims an advantage in replacing the operator with more mnemonic format method nameand not distinguishing between single and multiple substitution values the former may make the method appear simpler to beginners at first glance ("formatmay be easier to parse than multiple "%characters)though this probably varies per reader and seems minor some may see the latter difference as more significant--with the format expressiona single value can be given by itselfbut multiple values must be enclosed in tuple' ' ' % ( ' single value multiple values tuple technicallythe formatting expression accepts either single substitution valueor tuple of one or more items as consequencebecause single item can be given either by itself or within tuplea tuple to be formatted must be provided as nested tuple -- perhaps rare but plausible case'% ' '% ( ,' '% (( ,),'( ,)single valueby itself single valuein tuple single value that is tuple the formatting methodon the other handtightens this up by accepting only general function arguments in both casesinstead of requiring tuple both for multiple values or single value that is tuple'{ }format( ' '{ { }format( ' single value '{ }format( ' '{ }format(( ,)'( ,)single valueby itself multiple values single value that is tuple string formatting method calls
809
values in tuple and ignore the nontupled optionthe expression is essentially the same as the method call here moreoverthe method incurs price in inflated code size to achieve its constrained usage mode given the expression' wide use over python' historythis issue may be more theoretical than practicaland may not justify porting existing code to new tool that is so similar to that it seeks to subsume functions versus expressionsa minor convenience the final rationale for the format method--it' function that can appear where an expression cannot--requires more information about functions than we yet have at this point in the bookso we won' dwell on it here suffice it to say that both the str format method and the format built-in function can be passed to other functionsstored in other objectsand so on an expression like cannot directlybut this may be narrow-sighted--it' trivial to wrap any expression in one-line def or partial-line lambda once to turn it into function with the same properties (though finding reason to do so may be more challenging)def myformat(fmtargs)return fmt args see part iv myformat('% % '( )str format('{{}' call your function object versus calling the built-in otherfunction(myformatyour function is an object too in the endthis may not be an either/or choice while the expression still seems more pervasive in python codeboth formatting expressions and methods are available for use in python todayand most programmers will benefit from being familiar with both techniques for years to come that may double the work of newcomers to the language in this departmentbut in this bazaar of ideas we call the open source software worldthere always seems to be room for more plus one moretechnically speakingthere are (not formatting tools built into pythonif we include the obscure string module' template tool mentioned earlier now that we've seen the other twoi can show you how it compares the expression and method can be used as templating tools tooreferring to substitution values by name via dictionary keys or keyword arguments'%(num) %(title)sdict(num= title='strings'' strings see also the note about str format bug (or regressionin pythons and concerning generic empty substitution targets for object attributes that define no __format__ handler this impacted working example from this book' prior edition while it may be temporary regressionit does at the least underscore that this method is still bit of moving target--yet another reason to question the feature redundancy it implies string fundamentals
810
' strings'{num{title}format(**dict(num= title='strings')' stringsthe module' templating system allows values to be referenced by name tooprefixed by $as either dictionary keys or keywordsbut does not support all the utilities of the other two methods-- limitation that yields simplicitythe prime motivation for this toolimport string string template('$num $title' substitute({'num' 'title''strings'}' stringst substitute(num= title='strings'' stringst substitute(dict(num= title='strings')' stringssee python' manuals for more details it' possible that you may see this alternative (as well as additional tools in the third-party domainin python code toothankfully this technique is simpleand is used rarely enough to warrant its limited coverage here the best bet for most newcomers today is to learn and use %str formator both general type categories now that we've explored the first of python' collection objectsthe stringlet' close this by defining few general type concepts that will apply to most of the types we look at from here on with regard to built-in typesit turns out that operations work the same for all the types in the same categoryso we'll only need to define most of these ideas once we've only examined numbers and strings so farbut because they are representative of two of the three major type categories in pythonyou already know more about several other types than you might think types share operation sets by categories as you've learnedstrings are immutable sequencesthey cannot be changed in place (the immutable part)and they are positionally ordered collections that are accessed by offset (the sequence partit so happens that all the sequences we'll study in this part of the book respond to the same sequence operations shown in this at work on strings--concatenationindexingiterationand so on more formallythere are three major type (and operationcategories in python that have this generic naturenumbers (integerfloating-pointdecimalfractionotherssupport additionmultiplicationetc sequences (stringsliststuplessupport indexingslicingconcatenationetc general type categories
811
support indexing by keyetc ' including the python byte strings and unicode strings mentioned at the start of this under the general "stringslabel here (see sets are something of category unto themselves (they don' map keys to values and are not positionally ordered sequences)and we haven' yet explored mappings on our in-depth tour (we will in the next howevermany of the other types we will encounter will be similar to numbers and strings for examplefor any sequence objects and yx makes new sequence object with the contents of both operands makes new sequence object with copies of the sequence operand in other wordsthese operations work the same way on any kind of sequenceincluding stringsliststuplesand some user-defined object types the only difference is that the new result object you get back is of the same type as the operands and --if you concatenate listsyou get back new listnot string indexingslicingand other sequence operations work the same on all sequencestoothe type of the objects being processed tells python which flavor of the task to perform mutable types can be changed in place the immutable classification is an important constraint to be aware ofyet it tends to trip up new users if an object type is immutableyou cannot change its value in placepython raises an error if you try insteadyou must run code to make new object containing the new value the major core types in python break down as followsimmutables (numbersstringstuplesfrozensetsnone of the object types in the immutable category support in-place changesthough we can always run expressions to make new objects and assign their results to variables as needed mutables (listsdictionariessetsbytearrayconverselythe mutable types can always be changed in place with operations that do not create new objects although such objects can be copiedin-place changes support direct modification generallyimmutable types give some degree of integrity by guaranteeing that an object won' be changed by another part of program for refresher on why this matterssee the discussion of shared object references in to see how listsdictionariesand tuples participate in type categorieswe need to move ahead to the next string fundamentals
812
in this we took an in-depth tour of the string object type we learned about coding string literalsand we explored string operationsincluding sequence expressionsstring method callsand string formatting with both expressions and method calls along the waywe studied variety of concepts in depthsuch as slicingmethod call syntaxand triple-quoted block strings we also defined some core ideas common to variety of typessequencesfor exampleshare an entire set of operations in the next we'll continue our types tour with look at the most general object collections in python--lists and dictionaries as you'll findmuch of what you've learned here will apply to those types as well and as mentioned earlierin the final part of this book we'll return to python' string model to flesh out the details of unicode text and binary datawhich are of interest to somebut not allpython programmers before moving onthoughhere' another quiz to review the material covered here test your knowledgequiz can the string find method be used to search list can string slice expression be used on list how would you convert character to its ascii integer codehow would you convert the other wayfrom an integer to character how might you go about changing string in python given string with the value " ,pa, "name two ways to extract the two characters in the middle how many characters are there in the string " \nb\ \ " why might you use the string module instead of string method callstest your knowledgeanswers nobecause methods are always type-specificthat isthey only work on single data type expressions like + and built-in functions like len(xare genericthoughand may work on variety of types in this casefor instancethe in membership expression has similar effect as the string findbut it can be used to search both strings and lists in python xthere is some attempt to group methods by categories (for examplethe mutable sequence types list and bytearray have similar method sets)but methods are still more type-specific than other operation sets yes unlike methodsexpressions are generic and apply to many types in this casethe slice expression is really sequence operation--it works on any type of setest your knowledgeanswers
813
quence objectincluding stringslistsand tuples the only difference is that when you slice listyou get back new list the built-in ord(sfunction converts from one-character string to an integer character codechr(iconverts from the integer code back to string keep in mindthoughthat these integers are only ascii codes for text whose characters are drawn only from ascii character set in the unicode modeltext strings are really sequences of unicode code point identifying integerswhich may fall outside the -bit range of numbers reserved by ascii (more on unicode in and strings cannot be changedthey are immutable howeveryou can achieve similar effect by creating new string--by concatenatingslicingrunning formatting expressionsor using method call like replace--and then assigning the result back to the original variable name you can slice the string using [ : ]or split on the comma and index the string using split(',')[ try these interactively to see for yourself six the string " \nb\ \ dcontains the characters anewline (\ )bbinary ( hex escape \ )binary (an octal escape \ )and pass the string to the built-in len function to verify thisand print each of its character' ord results to see the actual code point (identifying numbervalues see table - for more details on escapes you should never use the string module instead of string object method calls today --it' deprecatedand its calls are removed completely in python the only valid reason for using the string module at all today is for its other toolssuch as predefined constants you might also see it appear in what is now very old and dusty python code (and books of the misty past--like the string fundamentals
814
lists and dictionaries now that we've learned about numbers and stringsthis moves on to give the full story on python' list and dictionary object types--collections of other objectsand the main workhorses in almost all python scripts as you'll seeboth types are remarkably flexiblethey can be changed in placecan grow and shrink on demandand may contain and be nested in any other kind of object by leveraging these typesyou can build up and process arbitrarily rich information structures in your scripts lists the next stop on our built-in object tour is the python list lists are python' most flexible ordered collection object type unlike stringslists can contain any sort of objectnumbersstringsand even other lists alsounlike stringslists may be changed in place by assignment to offsets and sliceslist method callsdeletion statementsand more--they are mutable objects python lists do the work of many of the collection data structures you might have to implement manually in lower-level languages such as here is quick look at their main properties python lists areordered collections of arbitrary objects from functional viewlists are just places to collect other objects so you can treat them as groups lists also maintain left-to-right positional ordering among the items they contain ( they are sequencesaccessed by offset just as with stringsyou can fetch component object out of list by indexing the list on the object' offset because items in lists are ordered by their positionsyou can also do tasks such as slicing and concatenation variable-lengthheterogeneousand arbitrarily nestable unlike stringslists can grow and shrink in place (their lengths can vary)and they can contain any sort of objectnot just one-character strings (they're heterogene
815
nestingyou can create lists of lists of listsand so on of the category "mutable sequencein terms of our type category qualifierslists are mutable ( can be changed in placeand can respond to all the sequence operations used with stringssuch as indexingslicingand concatenation in factsequence operations work the same on lists as they do on stringsthe only difference is that sequence operations such as concatenation and slicing return new lists instead of new strings when applied to lists because lists are mutablehoweverthey also support other operations that strings don'tsuch as deletion and index assignment operationswhich change the lists in place arrays of object references technicallypython lists contain zero or more references to other objects lists might remind you of arrays of pointers (addressesif you have background in some other languages fetching an item from python list is about as fast as indexing arrayin factlists really are arrays inside the standard python interpreternot linked structures as we learned in thoughpython always follows reference to an object whenever the reference is usedso your program deals only with objects whenever you assign an object to data structure component or variable namepython always stores reference to that same objectnot copy of it (unless you request copy explicitlyas preview and referencetable - summarizes common and representative list object operations it is fairly complete for python but for the full storyconsult the python standard library manualor run help(listor dir(listcall interactively for complete list of list methods--you can pass in real listor the word listwhich is the name of the list data type the set of methods here is especially prone to change-in facttwo are new as of python table - common list literals and operations operation interpretation [an empty list [ 'abc' {}four itemsindexes ['bob' ['dev''mgr']nested sublists list('spam'list of an iterable' itemslist of successive integers list(range(- ) [iindexindex of indexslicelength [ ][jl[ :jlen(ll lists and dictionaries concatenaterepeat
816
interpretation for in lprint(xiterationmembership in append( methodsgrowing extend([ , , ] insert(ixl index(xmethodssearching count(xl sort(methodssortingreversingl reverse(copying ( +)clearing ( + copy( clear( pop(imethodsstatementsshrinking remove(xdel [idel [ :jl[ : [ [ index assignmentslice assignment [ : [ , , [ ** for in range( )list comprehensions and maps (list(map(ord'spam')when written down as literal expressiona list is coded as series of objects (reallyexpressions that return objectsin square bracketsseparated by commas for instancethe second row in table - assigns the variable to four-item list nested list is coded as nested square-bracketed series (row )and the empty list is just squarebracket pair with nothing inside (row many of the operations in table - should look familiaras they are the same sequence operations we put to work on strings earlier--indexingconcatenationiterationand so on lists also respond to list-specific method calls (which provide utilities such as sortingreversingadding items to the endetc )as well as in-place change operations in practiceyou won' see many lists written out like this in list-processing programs it' more common to see code that processes lists constructed dynamically (at runtime)from user inputsfile contentsand so on in factalthough it' important to master literal syntaxmany data structures in python are built by running program code at runtime lists
817
for change operations because they are mutable object type lists in action perhaps the best way to understand lists is to see them at work let' once again turn to some simple interpreter interactions to illustrate the operations in table - basic list operations because they are sequenceslists support many of the same operations as strings for examplelists respond to the and operators much like strings--they mean concatenation and repetition here tooexcept that the result is new listnot stringpython len([ ] [ [ [ ['ni!' ['ni!''ni!''ni!''ni!'length concatenation repetition although the operator works the same for lists and stringsit' important to know that it expects the same sort of sequence on both sides--otherwiseyou get type error when the code runs for instanceyou cannot concatenate list and string unless you first convert the list to string (using tools such as str or formattingor convert the string to list (the list built-in function does the trick)str([ ]" '[ ] [ list(" "[ ' '' 'same as "[ ]" same as [ [" "" "list iteration and comprehensions more generallylists respond to all the sequence operations we used on strings in the prior including iteration tools in [ true for in [ ]print(xend=' membership iteration ( usesprint ,we will talk more formally about for iteration and the range built-ins of table - in because they are related to statement syntax in shortfor loops step through items in any sequence from left to rightexecuting one or more statements for each itemrange produces successive integers lists and dictionaries
818
in and expanded on in their basic operation is straightforwardthough--as introduced in list comprehensions are way to build new list by applying an expression to each item in sequence (reallyin any iterable)and are close relatives to for loopsres [ for in 'spam'res ['ssss''pppp''aaaa''mmmm'list comprehensions this expression is functionally equivalent to for loop that builds up list of results manuallybut as we'll learn in later list comprehensions are simpler to code and likely faster to run todayres [for in 'spam'res append( res ['ssss''pppp''aaaa''mmmm'list comprehension equivalent as also introduced briefly in the map built-in function does similar workbut applies function to items in sequence and collects all the results in new listlist(map(abs[- - ])[ map function across sequence because we're not quite ready for the full iteration storywe'll postpone further details for nowbut watch for similar comprehension expression for dictionaries later in this indexingslicingand matrixes because lists are sequencesindexing and slicing work the same way for lists as they do for strings howeverthe result of indexing list is whatever type of object lives at the offset you specifywhile slicing list always returns new listl ['spam''spam''spam!' [ 'spam! [- 'spaml[ :['spam''spam!'offsets start at zero negativecount from the right slicing fetches sections one note herebecause you can nest lists and other object types within listsyou will sometimes need to string together index operations to go deeper into data structure for exampleone of the simplest ways to represent matrixes (multidimensional arraysin python is as lists with nested sublists here' basic two-dimensional list-based arraymatrix [[ ][ ][ ]lists in action
819
an item within the rowmatrix[ [ matrix[ ][ matrix[ ][ matrix [[ ][ ][ ]matrix[ ][ notice in the preceding interaction that lists can naturally span multiple lines if you want them to because they are contained by pair of bracketsthe " here are python' continuation line prompt (see for comparable code without the "sand watch for more on syntax in the next part of the bookfor more on matrixeswatch later in this for dictionary-based matrix representationwhich can be more efficient when matrixes are largely empty we'll also continue this thread in where we'll write additional matrix codeespecially with list comprehensions for high-powered numeric workthe numpy extension mentioned in and provides other ways to handle matrixes changing lists in place because lists are mutablethey support operations that change list object in place that isthe operations in this section all modify the list object directly--overwriting its former value--without requiring that you make new copyas you had to for strings because python deals only in object referencesthis distinction between changing an object in place and creating new object mattersas discussed in if you change an object in placeyou might impact more than one reference to it at the same time index and slice assignments when using listyou can change its contents by assigning to either particular item (offsetor an entire section (slice) ['spam''spam''spam!' [ 'eggsl ['spam''eggs''spam!' [ : ['eat''more' ['eat''more''spam!' lists and dictionaries index assignment slice assignmentdelete+insert replaces items ,
820
directlyrather than generating new list object for the result index assignment in python works much as it does in and most other languagespython replaces the single object reference at the designated offset with new one slice assignmentthe last operation in the preceding examplereplaces an entire section of list in single step because it can be bit complexit is perhaps best thought of as combination of two steps deletion the slice you specify to the left of the is deleted insertion the new items contained in the iterable object to the right of the are inserted into the list on the leftat the place where the old slice was deleted this isn' what really happensbut it can help clarify why the number of items inserted doesn' have to match the number of items deleted for instancegiven list of two or more itemsan assignment [ : ]=[ , replaces one item with two--python first deletes the one-item slice at [ : (from offset up to but not including offset )then inserts both and where the deleted slice used to be this also explains why the second slice assignment in the following is really an insert --python replaces an empty slice at [ : with two itemsand why the third is really deletion--python deletes the slice (the item at offset )and then inserts nothingl [ [ : [ [ [ : [ [ [ : [ [ replacement/insertion insertion (replace nothingdeletion (insert nothingin effectslice assignment replaces an entire sectionor "column,all at once--even if the column or its replacement is empty because the length of the sequence being assigned does not have to match the length of the slice being assigned toslice assignment can be used to replace (by overwriting)expand (by inserting)or shrink (by deletingthe subject list it' powerful operationbut franklyone that you may not see very often in practice there are often more straightforward and mnemonic ways to replaceinsertand delete (concatenationand the insertpopand remove list methodsfor example)which python programmers tend to prefer in practice this description requires elaboration when the value and the slice being assigned overlapl[ : ]= [ : ]for instanceworks fine because the value to be inserted is fetched before the deletion happens on the left lists in action
821
front of the list--per the next section' method coveragesomething the list' extend does more mnemonically at list endl [ [: [ insert all at : an empty slice at front [ [len( ):[ insert all at len( ):an empty slice at end [ extend([ ]insert all at endnamed method [ list method calls like stringspython list objects also support type-specific method callsmany of which change the subject list in placel ['eat''more''spam!' append('please' ['eat''more''spam!''please' sort( ['spam!''eat''more''please'append method calladd item at end sort list items (' ' 'methods were introduced in in briefthey are functions (reallyobject attributes that reference functionsthat are associated with and act upon particular objects methods provide type-specific toolsthe list methods presented herefor instanceare generally available only for lists perhaps the most commonly used list method is appendwhich simply tacks single item (object referenceonto the end of the list unlike concatenationappend expects you to pass in single objectnot list the effect of append(xis similar to +[ ]but while the former changes in placethe latter makes new list the sort method orders the list' items herebut merits section of its own more on sorting lists another commonly seen methodsortorders list in placeit uses python standard comparison tests (herestring comparisonsbut applicable to every object type)and unlike concatenationappend doesn' have to generate new objectsso it' usually faster than too you can also mimic append with the clever slice assignments of the prior sectionl[len( ):]=[xis like append( )and [: ]=[xis like appending at the front of list both delete an empty slice and insert xchanging in place quicklylike append both are arguably more complex than list methodsthough for instancel insert( xcan also append an item to the front of listand seems noticeably more mnemonicl insert(len( )xinserts one object at the end toobut unless you like typingyou might as well use append( ) lists and dictionaries
822
arguments-- special "name=valuesyntax in function calls that specifies passing by name and is often used for giving configuration options in sortsthe reverse argument allows sorts to be made in descending instead of ascending orderand the key argument gives one-argument function that returns the value to be used in sorting--the string object' standard lower case converter in the following (though its newer casefold may handle some types of unicode text better) ['abc''abd''abe' sort( ['abd''abe''abc' ['abc''abd''abe' sort(key=str lowerl ['abc''abd''abe' ['abc''abd''abe' sort(key=str lowerreverse=truel ['abe''abd''abc'sort with mixed case normalize to lowercase change sort order the sort key argument might also be useful when sorting lists of dictionariesto pick out sort key by indexing each dictionary we'll study dictionaries later in this and you'll learn more about keyword function arguments in part iv comparison and sorts in xin python xrelative magnitude comparisons of differently typed objects ( string and listwork--the language defines fixed ordering among different typeswhich is deterministicif not aesthetically pleasing that isthe ordering is based on the names of the types involvedall integers are less than all stringsfor examplebecause "intis less than "strcomparisons never automatically convert typesexcept when comparing numeric type objects in python xthis has changedmagnitude comparison of mixed types raises an exception instead of falling back on the fixed cross-type ordering because sorting uses comparisons internallythis means that [ 'spam'sort(succeeds in python but will raise an exception in python sorting mixed-types fails by proxy python also no longer supports passing in an arbitrary comparison function to sortsto implement different orderings the suggested workaround is to use the key=func keyword argument to code value transformations during the sortand use the reverse=true keyword argument to change the sort order to descending these were the typical uses of comparison functions in the past lists in action
823
placebut don' return the list as result (technicallythey both return value called noneif you say something like = append( )you won' get the modified value of (in factyou'll lose the reference to the list altogether!when you use attributes such as append and sortobjects are changed as side effectso there' no reason to reassign partly because of such constraintssorting is also available in recent pythons as builtin functionwhich sorts any collection (not just listsand returns new list for the result (instead of in-place changes) ['abc''abd''abe'sorted(lkey=str lowerreverse=true['abe''abd''abc'sorting built-in ['abc''abd''abe'sorted([ lower(for in ]reverse=true['abe''abd''abc'pretransform itemsdiffersnotice the last example here--we can convert to lowercase prior to the sort with list comprehensionbut the result does not contain the original list' values as it does with the key argument the latter is applied temporarily during the sortinstead of changing the values to be sorted altogether as we move alongwe'll see contexts in which the sorted built-in can sometimes be more useful than the sort method other common list methods like stringslists have other methods that perform other specialized operations for instancereverse reverses the list in-placeand the extend and pop methods insert multiple items at and delete an item from the end of the listrespectively there is also reversed built-in function that works much like sorted and returns new result objectbut it must be wrapped in list call in both and here because its result is an iterator that produces results on demand (more on iterators later) [ extend([ ] [ pop( [ reverse( [ list(reversed( )[ add many items at end (like in-place +delete and return last item (by default- in-place reversal method reversal built-in with result (iteratortechnicallythe extend method always iterates through and adds each item in an iterable objectwhereas append simply adds single item as is without iterating through it -- distinction that will be more meaningful by for nowit' enough to know that extend adds many itemsand append adds one in some types of programs lists and dictionaries
824
[ append( append( [ pop( [ push onto stack pop off stack the pop method also accepts an optional offset of the item to be deleted and returned (the default is the last item at offset - other list methods remove an item by value (remove)insert an item at an offset (insert)count the number of occurrences (count)and search for an item' offset (index-- search for the index of an itemnot to be confused with indexing!) ['spam''eggs''ham' index('eggs' insert( 'toast' ['spam''toast''eggs''ham' remove('eggs' ['spam''toast''ham' pop( 'toastl ['spam''ham' count('spam' index of an object (search/findinsert at position delete by value delete by position number of occurrences note that unlike other list methodscount and index do not change the list itselfbut return information about its content see other documentation sources or experiment with these calls interactively on your own to learn more about list methods other common list operations because lists are mutableyou can use the del statement to delete an item or section in placel ['spam''eggs''ham''toast'del [ delete one item ['eggs''ham''toast'del [ :delete an entire section same as [ :[['eggs'as we saw earlierbecause slice assignment is deletion plus an insertionyou can also delete section of list by assigning an empty list to slice ( [ : ]=[])python deletes lists in action
825
indexon the other handjust stores reference to the empty list object in the specified slotrather than deleting an iteml ['already''got''one' [ :[ ['already' [ [ [[]although all the operations just discussed are typicalthere may be additional list methods and operations not illustrated here the method setfor examplemay change over timeand in fact has in python --its new copy(method makes top-level copy of the listmuch like [:and list( )but is symmetric with copy in sets and dictionaries for comprehensive and up-to-date list of type toolsyou should always consult python' manualspython' dir and help functions (which we first met in )or one of the reference texts mentioned in the preface and because it' such common hurdlei' also like to remind you again that all the in-place change operations discussed here work only for mutable objectsthey won' work on strings (or tuplesdiscussed in )no matter how hard you try mutability is an inherent property of each object type dictionaries along with listsdictionaries are one of the most flexible built-in data types in python if you think of lists as ordered collections of objectsyou can think of dictionaries as unordered collectionsthe chief distinction is that in dictionariesitems are stored and fetched by keyinstead of by positional offset while lists can serve roles similar to arrays in other languagesdictionaries take the place of recordssearch tablesand any other sort of aggregation where item names are more meaningful than item positions for exampledictionaries can replace many of the searching algorithms and data structures you might have to implement manually in lower-level languages--as highly optimized built-in typeindexing dictionary is very fast search operation dictionaries also sometimes do the work of recordsstructsand symbol tables used in other languagescan be used to represent sparse (mostly emptydata structuresand much more here' rundown of their main properties python dictionaries areaccessed by keynot offset position dictionaries are sometimes called associative arrays or hashes (especially by users of other scripting languagesthey associate set of values with keysso you can fetch an item out of dictionary using the key under which you originally stored it you use the same indexing operation to get components in dictionary as you do in listbut the index takes the form of keynot relative offset lists and dictionaries
826
unlike in listitems stored in dictionary aren' kept in any particular orderin factpython pseudo-randomizes their left-to-right order to provide quick lookup keys provide the symbolic (not physicallocations of items in dictionary variable-lengthheterogeneousand arbitrarily nestable like listsdictionaries can grow and shrink in place (without new copies being made)they can contain objects of any typeand they support nesting to any depth (they can contain listsother dictionariesand so oneach key can have just one associated valuebut that value can be collection of multiple objects if neededand given value can be stored under any number of keys of the category "mutable mappingyou can change dictionaries in place by assigning to indexes (they are mutable)but they don' support the sequence operations that work on strings and lists because dictionaries are unordered collectionsoperations that depend on fixed positional order ( concatenationslicingdon' make sense insteaddictionaries are the only built-incore type representatives of the mapping category-objects that map keys to values other mappings in python are created by imported modules tables of object references (hash tablesif lists are arrays of object references that support access by positiondictionaries are unordered tables of object references that support access by key internallydictionaries are implemented as hash tables (data structures that support very fast retrieval)which start small and grow on demand moreoverpython employs optimized hashing algorithms to find keysso retrieval is quick like listsdictionaries store object references (not copiesunless you ask for them explicitlyfor reference and preview againtable - summarizes some of the most common and representative dictionary operationsand is relatively complete as of python as usualthoughsee the library manual or run dir(dictor help(dictcall for complete list--dict is the name of the type when coded as literal expressiona dictionary is written as series of key:value pairsseparated by commasenclosed in curly braces an empty dictionary is an empty set of bracesand you can nest dictionaries by simply coding one as value inside another dictionaryor within list or tuple as for listsyou might not see dictionaries coded in full using literals very often--programs rarely know all their data before they are runand more typically extract it dynamically from usersfilesand so on lists and dictionaries are grown in different waysthough in the next section you'll see that you often build up dictionaries by assigning to new keys at runtimethis approach fails for listswhich are commonly grown with append or extend instead dictionaries
827
operation interpretation {empty dictionary {'name''bob''age' two-item dictionary {'cto'{'name''bob''age' }nesting dict(name='bob'age= alternative construction techniquesd dict([('name''bob')('age' )]keywordskey/value pairszipped key/value pairskey lists dict(zip(keyslistvalueslist) dict fromkeys(['name''age'] ['name'indexing by key ['cto']['age''agein membershipkey present test keys(methodsall keysd values(all valuesd items(all key+value tuplesd copy(copy (top-level) clear(clear (remove all items) update( merge by keysd get(keydefault?fetch by keyif absent default (or none) pop(keydefault?remove by keyif absent default (or errord setdefault(keydefault?fetch by keyif absent set default (or none) popitem(remove/return any (keyvaluepairetc len(dlengthnumber of stored entries [key adding/changing keys del [keydeleting entries by key list( keys()dictionary views (python xd keys( keys( viewkeys() viewvalues(dictionary views (python {xx* for in range( )dictionary comprehensions (python dictionaries in action as table - suggestsdictionaries are indexed by keyand nested dictionary entries are referenced by series of indexes (keys in square bracketswhen python creates dictionaryit stores its items in any left-to-right order it choosesto fetch value back lists and dictionaries
828
to the interpreter to get feel for some of the dictionary operations in table - basic dictionary operations in normal operationyou create dictionaries with literals and store and access items by key with indexingpython {'spam' 'ham' 'eggs' ['spam' {'eggs' 'spam' 'ham' make dictionary fetch value by key order is "scrambledherethe dictionary is assigned to the variable dthe value of the key 'spamis the integer and so on we use the same square bracket syntax to index dictionaries by key as we did to index lists by offsetbut here it means access by keynot by position notice the end of this example--much like setsthe left-to-right order of keys in dictionary will almost always be different from what you originally typed this is on purposeto implement fast key lookup ( hashing)keys need to be reordered in memory that' why operations that assume fixed left-to-right order ( slicingconcatenationdo not apply to dictionariesyou can fetch values only by keynot by position technicallythe ordering is pseudo-random--it' not truly random (you might be able to decipher it given python' source code and lot of time to kill)but it' arbitraryand might vary per release and platformand even per interactive session in python the built-in len function works on dictionariestooit returns the number of items stored in the dictionary orequivalentlythe length of its keys list the dictionary in membership operator allows you to test for key existenceand the keys method returns all the keys in the dictionary the latter of these can be useful for processing dictionaries sequentiallybut you shouldn' depend on the order of the keys list because the keys result can be used as normal listhoweverit can always be sorted if order matters (more on sorting and dictionaries later)len( 'hamin true list( keys()['eggs''spam''ham'number of entries in dictionary key membership test alternative create new list of ' keys observe the second expression in this listing as mentioned earlierthe in membership test used for strings and lists also works on dictionaries--it checks whether key is stored in the dictionary technicallythis works because dictionaries define iterators that step through their keys lists automatically other types provide iterators that reflect dictionaries in action
829
iterators more formally in and also note the syntax of the last example in this listing we have to enclose it in list call in python for similar reasons--keys in returns an iterable objectinstead of physical list the list call forces it to produce all its values at once so we can print them interactivelythough this call isn' required some other contexts in xkeys builds and returns an actual listso the list call isn' even needed to display resultmore on this later in this changing dictionaries in place let' continue with our interactive session dictionarieslike listsare mutableso you can changeexpandand shrink them in place without making new dictionariessimply assign value to key to change or create an entry the del statement works heretooit deletes the entry associated with the key specified as an index notice also the nesting of list inside dictionary in this example (the value of the key 'ham'all collection data types in python can nest inside each other arbitrarilyd {'eggs' 'spam' 'ham' ['ham'['grill''bake''fry'change entry (value=listd {'eggs' 'spam' 'ham'['grill''bake''fry']del ['eggs' {'spam' 'ham'['grill''bake''fry']delete entry ['brunch''baconadd new entry {'brunch''bacon''spam' 'ham'['grill''bake''fry']like listsassigning to an existing index in dictionary changes its associated value unlike listshoweverwhenever you assign new dictionary key (one that hasn' been assigned beforeyou create new entry in the dictionaryas was done in the previous example for the key 'brunchthis doesn' work for lists because you can only assign to existing list offsets--python considers an offset beyond the end of list out of bounds and raises an error to expand listyou need to use tools such as the append method or slice assignment instead more dictionary methods dictionary methods provide variety of type-specific tools for instancethe dictionary values and items methods return all of the dictionary' values and (key,valuepair tuplesrespectivelyalong with keysthese are useful in loops that need to step through dictionary entries one by one (we'll start coding examples of such loops in the next lists and dictionaries
830
them in list call there to collect their values all at once for displayd {'spam' 'ham' 'eggs' list( values()[ list( items()[('eggs' )('spam' )('ham' )in realistic programs that gather data as they runyou often won' be able to predict what will be in dictionary before the program is launchedmuch less when it' coded fetching nonexistent key is normally an errorbut the get method returns default value--noneor passed-in default--if the key doesn' exist it' an easy way to fill in default for key that isn' presentand avoid missing-key error when your program can' anticipate contents ahead of timed get('spam' print( get('toast')none get('toast' key that is there key that is missing the update method provides something similar to concatenation for dictionariesthough it has nothing to do with left-to-right ordering (againthere is no such thing in dictionariesit merges the keys and values of one dictionary into anotherblindly overwriting values of the same key if there' clashd {'eggs' 'spam' 'ham' {'toast': 'muffin': lots of delicious scrambled order here update( {'eggs' 'muffin' 'toast' 'spam' 'ham' notice how mixed up the key order is in the last resultagainthat' just how dictionaries work finallythe dictionary pop method deletes key from dictionary and returns the value it had it' similar to the list pop methodbut it takes key instead of an optional positionpop dictionary by key {'eggs' 'muffin' 'toast' 'spam' 'ham' pop('muffin' pop('toast'delete and return from key {'eggs' 'spam' 'ham' pop list by position ['aa''bb''cc''dd' pop('dddelete and return from the end dictionaries in action
831
['aa''bb''cc' pop( 'bbl ['aa''cc'delete from specific position dictionaries also provide copy methodwe'll revisit this in as it' way to avoid the potential side effects of shared references to the same dictionary in factdictionaries come with more methods than those listed in table - see the python library manualdir and helpor other reference sources for comprehensive list your dictionary ordering may varydon' be alarmed if your dictionaries print in different order than shown here as mentionedkey order is arbitraryand might vary per releaseplatformand interactive session in (and quite possibly per day of the weekand phase of the moon!most of the dictionary examples in this book reflect python ' key orderingbut it has changed both since and prior to your python' key order may varybut you're not supposed to care anyhowdictionaries are processed by keynot position programs shouldn' rely on the arbitrary order of keys in dictionarieseven if shown in books there are extension types in python' standard library that maintain insertion order among their keys--see ordereddict in the collections module--but they are hybrids that incur extra space and speed overheads to achieve their extra utilityand are not true dictionaries in shortkeys are kept redundantly in linked list to support sequence operations as we'll see in this module also implements namedtuple that allows tuple items to be accessed by both attribute name and sequence position-- sort of tuple/class/dictionary hybrid that adds processing steps and is not core object type in any event python' library manual has the full story on these and other extension types examplemovie database let' look at more realistic dictionary example in honor of python' namesakethe following example creates simple in-memory monty python movie databaseas table that maps movie release date years (the keysto movie titles (the valuesas codedyou fetch movie names by indexing on release year stringstable {' ''holy grail'' ''life of brian'' ''the meaning of life'year ' movie table[yearmovie 'the meaning of life lists and dictionaries keyvalue dictionary[key=value
832
print(year '\ttable[year] life of brian holy grail the meaning of life same asfor year in table keys(the last command uses for loopwhich we previewed in but haven' covered in detail yet if you aren' familiar with for loopsthis command simply iterates through each key in the table and prints tab-separated list of keys and their values we'll learn more about for loops in dictionaries aren' sequences like lists and stringsbut if you need to step through the items in dictionaryit' easy--calling the dictionary keys method returns all stored keyswhich you can iterate through with for if neededyou can index from key to value inside the for loop as you goas was done in this code in factpython also lets you step through dictionary' keys list without actually calling the keys method in most for loops for any dictionary dsaying for key in works the same as saying the complete for key in keys(this is really just another instance of the iterators mentioned earlierwhich allow the in membership operator to work on dictionaries as wellmore on iterators later in this book previewmapping values to keys notice how the prior table maps year to titlesbut not vice versa if you want to map the other way--titles to years--you can either code the dictionary differentlyor use methods like items that give searchable sequencesthough using them to best effect requires more background information than we yet havetable {'holy grail'' ''life of brian'' ''the meaning of life'' 'table['holy grail'' key=>value (title=>yearlist(table items()value=>key (year=>title[('the meaning of life'' ')('holy grail'' ')('life of brian'' ')[title for (titleyearin table items(if year =' '['holy grail'the last command here is in part preview for the comprehension syntax introduced in and covered in full in in shortit scans the dictionary' (keyvaluetuple pairs returned by the items methodselecting keys having specified value the net effect is to index backward--from value to keyinstead of key to value--useful if you want to store data just once and map backward only rarely (searching through sequences like this is generally much slower than direct key indexdictionaries in action
833
multiple ways to map values back to keys with bit of extra generalizable codek 'holy grailtable[ ' key=>value (normal usagev ' [key for (keyvaluein table items(if value = ['holy grail'[key for key in table keys(if table[key= ['holy grail'value=>key ditto note that both of the last two commands return list of titlesin dictionariesthere' just one value per keybut there may be many keys per value given value may be stored under multiple keys (yielding multiple keys per value)and value might be collection itself (supporting multiple values per keyfor more on this frontalso watch for dictionary inversion function in ' mapattrs py example--code that would surely stretch this preview past its breaking point if included here for this purposeslet' explore more dictionary basics dictionary usage notes dictionaries are fairly straightforward tools once you get the hang of thembut here are few additional pointers and reminders you should be aware of when using themsequence operations don' work dictionaries are mappingsnot sequencesbecause there' no notion of ordering among their itemsthings like concatenation (an ordered joiningand slicing (extracting contiguous sectionsimply don' apply in factpython raises an error when your code runs if you try to do such things assigning to new indexes adds entries keys can be created when you write dictionary literal (embedded in the code of the literal itself)or when you assign values to new keys of an existing dictionary object individually the end result is the same keys need not always be strings our examples so far have used strings as keysbut any other immutable objects work just as well for instanceyou can use integers as keyswhich makes the dictionary look much like list (when indexingat leasttuples may be used as dictionary keys tooallowing compound key values --such as dates and ip addresses--to have associated values user-defined class instance objects (discussed in part vican also be used as keysas long as they have the proper protocol methodsroughlythey need to tell python that their values are "hashableand thus won' changeas otherwise they would be useless as fixed keys mutable objects such as listssetsand other dictionaries don' work as keysbut are allowed as values lists and dictionaries
834
the last point in the prior list is important enough to demonstrate with few examples when you use listsit is illegal to assign to an offset that is off the end of the listl [ [ 'spamtraceback (most recent call last)file ""line in indexerrorlist assignment index out of range although you can use repetition to preallocate as big list as you'll need ( [ ]* )you can also do something that looks similar with dictionaries that does not require such space allocations by using integer keysdictionaries can emulate lists that seem to grow on offset assignmentd { [ 'spamd[ 'spamd { 'spam'hereit looks as if is -item listbut it' really dictionary with single entrythe value of the key is the string 'spamyou can access this structure with offsets much like listcatching nonexistent keys with get or in tests if requiredbut you don' have to allocate space for all the positions you might ever need to assign values to in the future when used like thisdictionaries are like more flexible equivalents of lists as another examplewe might also employ integer keys in our first movie database' code earlier to avoid quoting the yearalbeit at the expense of some expressiveness (keys cannot contain nondigit characters)table { 'holy grail' 'life of brian'keys are integersnot strings 'the meaning of life'table[ 'holy graillist(table items()[( 'life of brian')( 'the meaning of life')( 'holy grail')using dictionaries for sparse data structurestuple keys in similar waydictionary keys are also commonly leveraged to implement sparse data structures--for examplemultidimensional arrays where only few positions have values stored in themmatrix {matrix[( ) matrix[( ) matrix[(xyz) separates statementssee dictionaries in action
835
matrix {( ) ( ) herewe've used dictionary to represent three-dimensional array that is empty except for the two positions ( , , and ( , , the keys are tuples that record the coordinates of nonempty slots rather than allocating large and mostly empty threedimensional matrix to hold these valueswe can use simple two-item dictionary in this schemeaccessing an empty slot triggers nonexistent key exceptionas these slots are not physically storedmatrix[( , , )traceback (most recent call last)file ""line in keyerror( avoiding missing-key errors errors for nonexistent key fetches are common in sparse matrixesbut you probably won' want them to shut down your program there are at least three ways to fill in default value instead of getting such an error message--you can test for keys ahead of time in if statementsuse try statement to catch and recover from the exception explicitlyor simply use the dictionary get method shown earlier to provide default for keys that do not exist consider the first two of these previews for statement syntax we'll begin studying in if ( in matrixprint(matrix[( )]elseprint( tryprint(matrix[( )]except keyerrorprint( matrix get(( ) matrix get(( ) check for key before fetch see and for if/else try to index catch and recover see and for try/except existsfetch and return doesn' existuse default arg of thesethe get method is the most concise in terms of coding requirementsbut the if and try statements are much more general in scopeagainmore on these starting in nesting in dictionaries as you can seedictionaries can play many roles in python in generalthey can replace search data structures (because indexing by key is search operationand can represent many types of structured information for exampledictionaries are one of many ways lists and dictionaries
836
the same role as "recordsor "structsin other languages the followingfor examplefills out dictionary describing hypothetical personby assigning to new keys over time (if you are bobmy apologies for picking on your name in this book--it' easy to type!)rec {rec['name''bobrec['age' rec['job''developer/managerprint(rec['name']bob especially when nestedpython' built-in data types allow us to easily represent structured information the following again uses dictionary to capture object propertiesbut it codes it all at once (rather than assigning to each key separatelyand nests list and dictionary to represent structured property valuesrec {'name''bob''jobs'['developer''manager']'web''www bobs org/~bob''home'{'state''overworked''zip' }to fetch components of nested objectssimply string together indexing operationsrec['name''bobrec['jobs'['developer''manager'rec['jobs'][ 'managerrec['home']['zip' although we'll learn in part vi that classes (which group both data and logiccan be better in this record roledictionaries are an easy-to-use tool for simpler requirements for more on record representation choicessee also the upcoming sidebar "why you will caredictionaries versus listson page as well as its extension to tuples in and classes in also notice that while we've focused on single "recordwith nested data herethere' no reason we couldn' nest the record itself in largerenclosing database collection coded as list or dictionarythough an external file or formal database interface often plays the role of top-level container in realistic programsdb [db append(recdb append(otherdb[ ]['jobs'db {db['bob'rec list "databasea dictionary "databasedictionaries in action
837
db['bob']['jobs'later in the book we'll meet tools such as python' shelvewhich works much the same waybut automatically maps objects to and from files to make them permanent (watch for more in this sidebar "why you will caredictionary interfaceson page other ways to make dictionaries finallynote that because dictionaries are so usefulmore ways to build them have emerged over time in python and laterfor examplethe last two calls to the dict constructor (reallytype nameshown here have the same effect as the literal and keyassignment forms above them{'name''bob''age' traditional literal expression { ['name''bobd['age' assign by keys dynamically dict(name='bob'age= dict keyword argument form dict([('name''bob')('age' )]dict key/value tuples form all four of these forms create the same two-key dictionarybut they are useful in differing circumstancesthe first is handy if you can spell out the entire dictionary ahead of time the second is of use if you need to create the dictionary one field at time on the fly the third involves less typing than the firstbut it requires all keys to be strings the last is useful if you need to build up keys and values as sequences at runtime we met keyword arguments earlier when sortingthe third form illustrated in this code listing has become especially popular in python code todaysince it has less syntax (and hence there is less opportunity for mistakesas suggested previously in table - the last form in the listing is also commonly used in conjunction with the zip functionto combine separate lists of keys and values obtained dynamically at runtime (parsed out of data file' columnsfor instance)dict(zip(keyslistvalueslist)zipped key/value tuples form (aheadmore on zipping dictionary keys in the next section provided all the key' values are the same initiallyyou can also create dictionary with this special form--simply pass in list of keys and an initial value for all of the values (the default is none)dict fromkeys([' '' '] {' ' ' ' lists and dictionaries
838
python careeryou'll probably find uses for all of these dictionary-creation forms as you start applying them in realisticflexibleand dynamic python programs the listings in this section document the various ways to create dictionaries in both python and howeverthere is yet another way to create dictionariesavailable only in python and the dictionary comprehension expression to see how this last form lookswe need to move on to the next and final section of this why you will caredictionaries versus lists with all the objects in python' core types arsenalsome readers may be puzzled over the choice between lists and dictionaries in shortalthough both are flexible collections of other objectslists assign items to positionsand dictionaries assign them to more mnemonic keys because of thisdictionary data often carries more meaning to human readers for examplethe nested list structure in row of table - could be used to represent record tool ['bob' ['dev''mgr'] [ 'bobl[ [ ][ 'mgrlist-based "recordpositions/numbers for fields for some types of datathe list' access-by-position makes sense-- list of employees in companythe files in directoryor numeric matrixesfor example but more symbolic record like this may be more meaningfully coded as dictionary along the lines of row in table - with labeled fields replacing field positions (this is similar to record we coded in ) {'name''bob''age' 'jobs'['dev''mgr'] ['name''bobd['age'dictionary-based "record ['jobs'][ names mean more than numbers 'mgrfor varietyhere is the same record recoded with keywordswhich may seem even more readable to some human readersd dict(name='bob'age= jobs=['dev''mgr'] ['name''bobd['jobs'remove('mgr' {'jobs'['dev']'age' 'name''bob'in practicedictionaries tend to be best for data with labeled componentsas well as structures that can benefit from quickdirect lookups by nameinstead of slower linear searches as we've seenthey also may be better for sparse collections and collections that grow at arbitrary positions dictionaries in action
839
much like the keys of valueless dictionarythey don' map keys to valuesbut can often be used like dictionaries for fast lookups when there is no associated valueespecially in search routinesd { ['state 'true 'state in true set( add('state ''state in true visited-state dictionary samebut with sets watch for rehash of this record representation thread in the next where we'll see how tuples and named tuples compare to dictionaries in this roleas well as in where we'll learn how user-defined classes factor into this picturecombining both data and logic to process it dictionary changes in python and this has so far focused on dictionary basics that span releasesbut the dictionary' functionality has mutated in python if you are using python codeyou may come across some dictionary tools that either behave differently or are missing altogether in moreover coders have access to additional dictionary tools not available in xapart from two back-ports to specificallydictionaries in python xsupport new dictionary comprehension expressiona close cousin to list and set comprehensions return set-like iterable views instead of lists for the methods keysd valuesand items require new coding styles for scanning by sorted keysbecause of the prior point no longer support relative magnitude comparisons directly--compare manually instead no longer have the has_key method--the in membership test is used instead as later back-ports from xdictionaries in python (but not earlier in )support item in the prior list--dictionary comprehensions--as direct back-port from support item in the prior list--set-like iterable views--but do so with special method names viewkeysd viewvaluesd viewitems)their nonview methods return lists as before lists and dictionaries
840
but is presented here in the context of extensions because of its origin with that in mindlet' take look at what' new in dictionaries in and dictionary comprehensions in and as mentioned at the end of the prior sectiondictionaries in and can also be created with dictionary comprehensions like the set comprehensions we met in dictionary comprehensions are available only in and (not in and earlierlike the longstanding list comprehensions we met briefly in and earlier in this they run an implied loopcollecting the key/value results of expressions on each iteration and using them to fill out new dictionary loop variable allows the comprehension to use loop iteration values along the way to illustratea standard way to initialize dictionary dynamically in both and is to combine its keys and values with zipand pass the result to the dict call the zip built-in function is the hook that allows us to construct dictionary from key and value lists this way--if you cannot predict the set of keys and values in your codeyou can always build them up as lists and zip them together we'll study zip in detail in and after exploring statementsit' an iterable in xso we must wrap it in list call to show its results therebut its basic usage is otherwise straightforwardlist(zip([' '' '' '][ ])[(' ' )(' ' )(' ' )zip together keys and values dict(zip([' '' '' '][ ]) {' ' ' ' ' ' make dict from zip result in python and thoughyou can achieve the same effect with dictionary comprehension expression the following builds new dictionary with key/value pair for every such pair in the zip result (it reads almost the same in pythonbut with bit more formality) {kv for (kvin zip([' '' '' '][ ]) {' ' ' ' ' ' comprehensions actually require more code in this casebut they are also more general than this example implies--we can use them to map single stream of values to dictionaries as welland keys can be computed with expressions just like valuesd {xx * for in [ ] { orrange( {cc for in 'spam'loop over any iterable {' ''ssss'' ''pppp'' ''aaaa'' ''mmmm'dictionaries in action
841
{'eggs''eggs!''spam''spam!''ham''ham!'dictionary comprehensions are also useful for initializing dictionaries from keys listsin much the same way as the fromkeys method we met at the end of the preceding sectiond dict fromkeys([' '' '' '] {' ' ' ' ' ' initialize dict from keys { : for in [' '' '' '] {' ' ' ' ' ' samebut with comprehension dict fromkeys('spam' {' 'none' 'none' 'none' 'noneother iterablesdefault value {knone for in 'spam' {' 'none' 'none' 'none' 'nonelike related toolsdictionary comprehensions support additional syntax not shown hereincluding nested loops and if clauses unfortunatelyto truly understand dictionary comprehensionswe need to also know more about iteration statements and concepts in pythonand we don' yet have enough information to address that story well we'll learn much more about all flavors of comprehensions (listsetdictionaryand generatorin and so we'll defer further details until later we'll also revisit the zip built-in we used in this section in more detail in when we explore for loops dictionary views in (and via new methodsin the dictionary keysvaluesand items methods all return view objectswhereas in they return actual result lists this functionality is also available in python but in the guise of the specialdistinct method names listed at the start of this section ( ' normal methods still return simple listsso as to avoid breaking existing code)because of thisi'll refer to this as feature in this section view objects are iterableswhich simply means objects that generate result items one at timeinstead of producing the result list all at once in memory besides being iterabledictionary views also retain the original order of dictionary componentsreflect future changes to the dictionaryand may support set operations on the other handbecause they are not liststhey do not directly support operations like indexing or the list sort methodand do not display their items as normal list when printed (they do show their components as of python but not as listand are still divergence from lists and dictionaries
842
here it' enough to know that we have to run the results of these three methods through the list built-in if we want to apply list operations or display their values for examplein python (other version' outputs may differ slightly) dict( = = = {' ' ' ' ' ' keys( dict_keys([' '' '' ']list( [' '' '' 'makes view object in xnot list values( dict_values([ ]list( [ ditto for values and items views force real list in if needed items(dict_items([(' ' )(' ' )(' ' )]list( items()[(' ' )(' ' )(' ' ) [ list operations fail unless converted typeerror'dict_keysobject does not support indexing list( )[ 'bapart from result displays at the interactive promptyou will probably rarely even notice this changebecause looping constructs in python automatically force iterable objects to produce one result on each iterationfor in keys()print(kb iterators used automatically in loops in addition dictionaries still have iterators themselveswhich return successive keys--as in xit' still often not necessary to call keys directlyfor key in dprint(keyb still no need to call keys(to iterate unlike ' list resultsthoughdictionary views in are not carved in stone when created--they dynamically reflect future changes made to the dictionary after the view object has been createddictionaries in action
843
{' ' ' ' ' ' keys( values(list( [' '' '' 'list( [ views maintain same order as dictionary del [' ' {' ' ' ' change the dictionary in place list( [' '' 'list( [ reflected in any current view objects not true in xlists detached from dict dictionary views and sets also unlike ' list results ' view objects returned by the keys method are setlike and support common set operations such as intersection and unionvalues views are not set-likebut items results are if their (keyvaluepairs are unique and hashable (immutablegiven that sets behave much like valueless dictionaries (and may even be coded in curly braces like dictionaries in and )this is logical symmetry per set items are unordereduniqueand immutablejust like dictionary keys here is what keys views look like when used in set operations (continuing the prior section' session)dictionary value views are never set-likesince their items are not necessarily unique or immutablekv (dict_keys([' '' '])dict_values([ ]) {' ' {' '' '' 'keys (and some itemsviews are set-like {' ' typeerrorunsupported operand type(sfor &'dict_valuesand 'dictv {' ' values(typeerrorunsupported operand type(sfor &'dict_valuesand 'dict_valuesin set operationsviews may be mixed with other viewssetsand dictionariesdictionaries are treated the same as their keys views in this contextd {' ' ' ' ' ' keys( keys({' '' '' ' keys({' '{' ' keys({' ' {' ' lists and dictionaries intersect keys views intersect keys and set intersect keys and dict
844
{' '' '' '' 'union keys and set items views are set-like too if they are hashable--that isif they contain only immutable objectsd {' ' list( items()[(' ' ) items( keys({(' ' )' ' items( {(' ' )' 'items set-like if hashable union view and view dict treated same as its keys items({(' ' )(' ' ){(' ' )(' ' )(' ' )set of key/value pairs dict( items({(' ' )(' ' )}{' ' ' ' ' ' dict accepts iterable sets too see ' coverage of sets if you need refresher on these operations herelet' wrap up with three other quick coding notes for dictionaries sorting dictionary keys in first of allbecause keys does not return list in xthe traditional coding pattern for scanning dictionary by sorted keys in won' work in xd {' ' ' ' ' ' {' ' ' ' ' ' ks keys(sorting view object doesn' workks sort(attributeerror'dict_keysobject has no attribute 'sortto work around thisin you must either convert to list manually or use the sorted call (introduced in and covered in this on either keys view or the dictionary itselfks list(ksks sort(for in ksprint(kd[ ] {' ' ' ' ' ' ks keys(for in sorted(ks)print(kd[ ] force it to be list and then sort xomit outer parens in prints or you can use sorted(on the keys sorted(accepts any iterable sorted(returns its result dictionaries in action
845
of theseusing the dictionary' keys iterator is probably preferable in xand works in as welld {' ' ' ' ' ' for in sorted( )print(kd[ ] better yetsort the dict directly dict iterators return keys dictionary magnitude comparisons no longer work in secondlywhile in python dictionaries may be compared for relative magnitude directly with and so onin python this no longer works howeveryou can simulate it by comparing sorted keys lists manuallysorted( items()sorted( items()like dictionary equality tests ( = still work in xthough since we'll revisit this near the end of the next in the context of comparisons at largewe'll postpone further details here the has_key method is dead in xlong live infinallythe widely used dictionary has_key key presence test method is gone in insteaduse the in membership expressionor get with default test (of thesein is generally preferred) {' ' ' ' ' ' has_key(' ' onlytrue/false attributeerror'dictobject has no attribute 'has_key'cin true 'xin false if 'cin dprint('present' [' ']present print( get(' ') print( get(' ')none if get(' '!noneprint('present' [' ']present lists and dictionaries required in preferred in today branch on result fetch with default another option
846
and care about compatibility (or suspect that you might someday)here are some pointers of the changes we've met in this sectionthe first (dictionary comprehensionscan be coded only in and the second (dictionary viewscan be coded only in xand with special method names in howeverthe last three techniques--sortedmanual comparisonsand in--can be coded in today to ease migration in the future why you will caredictionary interfaces dictionaries aren' just convenient way to store information by key in your programs --some python extensions also present interfaces that look like and work the same as dictionaries for instancepython' interface to dbm access-by-key files looks much like dictionary that must be opened you store and fetch strings using key indexesimport dbm file dbm open("filename"file['key''datadata file['key'named anydbm in python link to file store data by key fetch data by key in you'll see that you can store entire python objects this waytooif you replace dbm in the preceding code with shelve (shelves are access-by-key databases that store persistent python objectsnot just stringsfor internet workpython' cgi script support also presents dictionary-like interface call to cgi fieldstorage yields dictionary-like object with one entry per input field on the client' web pageimport cgi form cgi fieldstorage(parse form data if 'namein formshowreply('helloform['name'valuethough dictionaries are the only core mapping typeall of these others are instances of mappingsand support most of the same operations once you learn dictionary interfacesyou'll find that they apply to variety of built-in tools in python for another dictionary use casesee also ' upcoming overview of json-- language-neutral data format used for databases and data transfer python dictionarieslistsand nested combinations of them can almost pass for records in this format as isand may be easily translated to and from formal json text strings with python' json standard library module summary in this we explored the list and dictionary types--probably the two most commonflexibleand powerful collection types you will see and use in python code we learned that the list type supports positionally ordered collections of arbitrary obsummary
847
type is similarbut it stores items by key instead of by position and does not maintain any reliable left-to-right order among its items both lists and dictionaries are mutableand so support variety of in-place change operations not available for stringsfor examplelists can be grown by append callsand dictionaries by assignment to new keys in the next we will wrap up our in-depth core object type tour by looking at tuples and files after thatwe'll move on to statements that code the logic that processes our objectstaking us another step toward writing complete programs before we tackle those topicsthoughhere are some quiz questions to review test your knowledgequiz name two ways to build list containing five integer zeros name two ways to build dictionary with two keys'aand ' 'each having an associated value of name four operations that change list object in place name four operations that change dictionary object in place why might you use dictionary instead of listtest your knowledgeanswers literal expression like [ and repetition expression like [ will each create list of five zeros in practiceyou might also build one up with loop that starts with an empty list and appends to it in each iterationwith append( list comprehension ([ for in range( )]could work heretoobut this is more work than you need to do for this answer literal expression such as {' ' ' ' or series of assignments like {} [' ' and [' ' would create the desired dictionary you can also use the newer and simpler-to-code dict( = = keyword formor the more flexible dict([(' ' )(' ' )]key/value sequences form orbecause all the values are the sameyou can use the special form dict fromkeys('ab' in and you can also use dictionary comprehension{ : for in 'ab'}though againthis may be overkill here the append and extend methods grow list in placethe sort and reverse methods order and reverse liststhe insert method inserts an item at an offsetthe remove and pop methods delete from list by value and by positionthe del statement deletes an item or sliceand index and slice assignment statements replace an item or entire section pick any four of these for the quiz dictionaries are primarily changed by assignment to new or existing keywhich creates or changes the key' entry in the table alsothe del statement deletes lists and dictionaries
848
placeand pop(keyremoves key and returns the value it had dictionaries also have othermore exotic in-place change methods not presented in this such as setdefaultsee reference sources for more details dictionaries are generally better when the data is labeled ( record with field namesfor example)lists are best suited to collections of unlabeled items (such as all the files in directorydictionary lookup is also usually quicker than searching listthough this might vary per program test your knowledgeanswers
849
tuplesfilesand everything else this rounds out our in-depth tour of the core object types in python by exploring the tuplea collection of other objects that cannot be changedand the filean interface to external files on your computer as you'll seethe tuple is relatively simple object that largely performs operations you've already learned about for strings and lists the file object is commonly used and full-featured tool for processing files on your computer because files are so pervasive in programmingthe basic overview of files here is supplemented by larger examples in later this also concludes this part of the book by looking at properties common to all the core object types we've met--the notions of equalitycomparisonsobject copiesand so on we'll also briefly explore other object types in python' toolboxincluding the none placeholder and the namedtuple hybridas you'll seealthough we've covered all the primary built-in typesthe object story in python is broader than 've implied thus far finallywe'll close this part of the book by taking look at set of common object type pitfalls and exploring some exercises that will allow you to experiment with the ideas you've learned this scope--filesas in on stringsour look at files here will be limited in scope to file fundamentals that most python programmers--including newcomers to programming--need to know in particularunicode text files were previewed in but we're going to postpone full coverage of them until as optional or deferred reading in the advanced topics part of this book for this purposewe'll assume any text files used will be encoded and decoded per your platform' defaultwhich may be utf- on windowsand ascii or other elsewhere (and if you don' know why this mattersyou probably don' need to up frontwe'll also assume that filenames encode properly on the underlying platformthough we'll stick with ascii names for portability here if unicode text and files is critical subject for youi suggest reading the preview for quick first lookand continuing on to
850
the file coverage here will apply both to typical text and binary files of the sort we'll meet hereas well as to more advanced file-processing modes you may choose to explore later tuples the last collection type in our survey is the python tuple tuples construct simple groups of objects they work exactly like listsexcept that tuples can' be changed in place (they're immutableand are usually written as series of items in parenthesesnot square brackets although they don' support as many methodstuples share most of their properties with lists here' quick look at the basics tuples areordered collections of arbitrary objects like strings and liststuples are positionally ordered collections of objects ( they maintain left-to-right order among their contents)like liststhey can embed any kind of object accessed by offset like strings and listsitems in tuple are accessed by offset (not by key)they support all the offset-based access operationssuch as indexing and slicing of the category "immutable sequencelike strings and liststuples are sequencesthey support many of the same operations howeverlike stringstuples are immutablethey don' support any of the in-place change operations applied to lists fixed-lengthheterogeneousand arbitrarily nestable because tuples are immutableyou cannot change the size of tuple without making copy on the other handtuples can hold any type of objectincluding other compound objects ( listsdictionariesother tuples)and so support arbitrary nesting arrays of object references like liststuples are best thought of as object reference arraystuples store access points to other objects (references)and indexing tuple is relatively quick table - highlights common tuple operations tuple is written as series of objects (technicallyexpressions that generate objects)separated by commas and normally enclosed in parentheses an empty tuple is just parentheses pair with nothing inside table - common tuple literals and operations operation interpretation (an empty tuple ( , one-item tuple (not an expressiont ( 'ni' four-item tuple 'ni' another four-item tuple (same as prior line tuplesfilesand everything else
851
interpretation ('bob'('dev''mgr')nested tuples tuple('spam'tuple of items in an iterable [iindexindex of indexslicelength [ ][jt[ :jlen(tconcatenaterepeat iterationmembership for in tprint( 'spamin [ * for in tmethods in and xsearchcount index('ni' count('ni'namedtuple('emp'['name''jobs']named tuple extension type tuples in action as usuallet' start an interactive session to explore tuples at work notice in table - that tuples do not have all the methods that lists have ( an append call won' work herethey dohoweversupport the usual sequence operations that we saw for both strings and lists( ( ( concatenation ( ( repetition ( [ ] [ : ( ( )indexingslicing tuple syntax peculiaritiescommas and parentheses the second and fourth entries in table - merit bit more explanation because parentheses can also enclose expressions (see )you need to do something special to tell python when single object in parentheses is tuple object and not simple expression if you really want single-item tuplesimply add trailing comma after the single itembefore the closing parenthesisx ( an integertuples
852
( , tuple containing an integer as special casepython also allows you to omit the opening and closing parentheses for tuple in contexts where it isn' syntactically ambiguous to do so for instancethe fourth line of table - simply lists four items separated by commas in the context of an assignment statementpython recognizes this as tupleeven though it doesn' have parentheses nowsome people will tell you to always use parentheses in your tuplesand some will tell you to never use parentheses in tuples (and still others have livesand won' tell you what to do with your tuples!the most common places where the parentheses are required for tuple literals are those whereparentheses matter--within function callor nested in larger expression commas matter--embedded in the literal of larger data structure like list or dictionaryor listed in python print statement in most other contextsthe enclosing parentheses are optional for beginnersthe best advice is that it' probably easier to use the parentheses than it is to remember when they are optional or required many programmers (myself includedalso find that parentheses tend to aid script readability by making the tuples more explicit and obviousbut your mileage may vary conversionsmethodsand immutability apart from literal syntax differencestuple operations (the middle rows in table - are identical to string and list operations the only differences worth noting are that the +*and slicing operations return new tuples when applied to tuplesand that tuples don' provide the same methods you saw for stringslistsand dictionaries if you want to sort tuplefor exampleyou'll usually have to either first convert it to list to gain access to sorting method call and make it mutable objector use the newer sorted built-in that accepts any sequence object (and other iterables-- term introduced in that we'll be more formal about in the next part of this book) ('cc''aa''dd''bb'tmp list(ttmp sort(tmp ['aa''bb''cc''dd' tuple(tmpt ('aa''bb''cc''dd'sorted( ['aa''bb''cc''dd' tuplesfilesand everything else make list from tuple' items sort the list make tuple from the list' items or use the sorted built-inand save two steps
853
then back to tuplereallyboth calls make new objectsbut the net effect is like conversion list comprehensions can also be used to convert tuples the followingfor examplemakes list from tupleadding to each item along the wayt ( [ for in tl [ list comprehensions are really sequence operations--they always build new listsbut they may be used to iterate over any sequence objectsincluding tuplesstringsand other lists as we'll see later in the bookthey even work on some things that are not physically stored sequences--any iterable objects will doincluding fileswhich are automatically read line by line given thisthey may be better called iteration tools although tuples don' have the same methods as lists and stringsthey do have two of their own as of python and --index and count work as they do for listsbut they are defined for tuple objectst ( index( index( count( tuple methods in and later offset of first appearance of offset of appearance after offset how many are thereprior to and tuples have no methods at all--this was an old python convention for immutable typeswhich was violated years ago on grounds of practicality with stringsand more recently with both numbers and tuples alsonote that the rule about tuple immutability applies only to the top level of the tuple itselfnot to its contents list inside tuplefor instancecan be changed as usualt ( [ ] [ 'spamthis failscan' change tuple itself typeerrorobject doesn' support item assignment [ ][ 'spamt ( ['spam' ] this workscan change mutables inside for most programsthis one-level-deep immutability is sufficient for common tuple roles whichcoincidentallybrings us to the next section why lists and tuplesthis seems to be the first question that always comes up when teaching beginners about tupleswhy do we need tuples if we have listssome of the reasoning may be historictuples
854
tuple as simple association of objects and list as data structure that changes over time in factthis use of the word "tuplederives from mathematicsas does its frequent use for row in relational database table the best answerhoweverseems to be that the immutability of tuples provides some integrity--you can be sure tuple won' be changed through another reference elsewhere in programbut there' no such guarantee for lists tuples and other immutablesthereforeserve similar role to "constantdeclarations in other languagesthough the notion of constantness is associated with objects in pythonnot variables tuples can also be used in places that lists cannot--for exampleas dictionary keys (see the sparse matrix example in some built-in operations may also require or imply tuples instead of lists ( the substitution values in string format expression)though such operations have often been generalized in recent years to be more flexible as rule of thumblists are the tool of choice for ordered collections that might need to changetuples can handle the other cases of fixed associations records revisitednamed tuples in factthe choice of data types is even richer than the prior section may have implied --today' python programmers can choose from an assortment of both built-in core typesand extension types built on top of them for examplein the prior sidebar "why you will caredictionaries versus listson page we saw how to represent record-like information with both list and dictionaryand noted that dictionaries offer the advantage of more mnemonic keys that label data as long as we don' require mutabilitytuples can serve similar roleswith positions for record fields like listsbob ('bob' ['dev''mgr']bob ('bob' ['dev''mgr']tuple record bob[ ]bob[ ('bob'['dev''mgr']access by position as for liststhoughfield numbers in tuples generally carry less information than the names of keys in dictionary here' the same record recoded as dictionary with named fieldsbob dict(name='bob'age= jobs=['dev''mgr']dictionary record bob {'jobs'['dev''mgr']'name''bob''age' bob['name']bob['jobs'('bob'['dev''mgr']access by key in factwe can convert parts of the dictionary to tuple if needed tuplesfilesand everything else
855
values to tuple (['dev''mgr']'bob' list(bob items()items to tuple list [('jobs'['dev''mgr'])('name''bob')('age' )but with bit of extra workwe can implement objects that offer both positional and named access to record fields for examplethe namedtuple utilityavailable in the standard library' collections module mentioned in implements an extension type that adds logic to tuples that allows components to be accessed by both position and attribute nameand can be converted to dictionary-like form for access by key if desired attribute names come from classes and are not exactly dictionary keysbut they are similarly mnemonicfrom collections import namedtuple rec namedtuple('rec'['name''age''jobs']bob rec('bob'age= jobs=['dev''mgr']bob rec(name='bob'age= jobs=['dev''mgr']import extension type make generated class named-tuple record bob[ ]bob[ ('bob'['dev''mgr']bob namebob jobs ('bob'['dev''mgr']access by position access by attribute converting to dictionary supports key-based behavior when neededo bob _asdict(dictionary-like form ['name'] ['jobs'access by key too ('bob'['dev''mgr'] ordereddict([('name''bob')('age' )('jobs'['dev''mgr'])]as you can seenamed tuples are tuple/class/dictionary hybrid they also represent classic tradeoff in exchange for their extra utilitythey require extra code (the two startup lines in the preceding examples that import the type and make the class)and incur some performance costs to work this magic (in shortnamed tuples build new classes that extend the tuple typeinserting property accessor method for each named field that maps the name to its position-- technique that relies on advanced topics we'll explore in part viiiand uses formatted code strings instead of class annotation tools like decorators and metaclasses stillthey are good example of the kind of custom data types that we can build on top of built-in types like tuples when extra utility is desired named tuples are available in python (where _asdict returns true dictionary)and perhaps earlierthough they rely on features relatively modern by python standards they are also extensionsnot core types--they live in the standard library and fall into the same category as ' fraction and decimal--so we'll delegate to the python library manual for more details as quick previewthoughboth tuples and named tuples support unpacking tuple assignmentwhich we'll study formally in as well as the iteration contexts tuples
856
named tuples accept these by namepositionor both)bob rec('bob' ['dev''mgr']nameagejobs bob namejobs ('bob'['dev''mgr']for both tuples and named tuples tuple assignment (for in bobprint(xprints bob ['dev''mgr'iteration context tuple-unpacking assignment doesn' quite apply to dictionariesshort of fetching and converting keys and values and assuming or imposing an positional ordering on them (dictionaries are not sequences)and iteration steps through keysnot values (notice the dictionary literal form herean alternative to dict)bob {'name''bob''age' 'jobs'['dev''mgr']jobnameage bob values(namejob dict equivalent (but order may vary('bob'['dev''mgr']for in bobprint(bob[ ]prints values for in bob values()print(xprints values step though keysindex values step through values view watch for final rehash of this record representation thread when we see how userdefined classes compare in as we'll findclasses label fields with names toobut can also provide program logic to process the record' data in the same package files you may already be familiar with the notion of fileswhich are named storage compartments on your computer that are managed by your operating system the last major built-in object type that we'll examine on our object types tour provides way to access those files inside python programs in shortthe built-in open function creates python file objectwhich serves as link to file residing on your machine after calling openyou can transfer strings of data to and from the associated external file by calling the returned file object' methods compared to the types you've seen so farfile objects are somewhat unusual they are considered core type because they are created by built-in functionbut they're not numberssequencesor mappingsand they don' respond to expression operatorsthey export only methods for common file-processing tasks most file methods are concerned with performing input from and output to the external file associated with file objectbut other file methods allow us to seek to new position in the fileflush output buffersand so on table - summarizes common file operations tuplesfilesand everything else
857
operation interpretation output open( ' :\spam'' 'create output file ('wmeans writeinput open('data'' 'create input file ('rmeans readinput open('data'same as prior line ('ris the defaultastring input read(read entire file into single string astring input read(nread up to next characters (or bytesinto string astring input readline(read next line (including \ newlineinto string alist input readlines(read entire file into list of line strings (with \noutput write(astringwrite string of characters (or bytesinto file output writelines(alistwrite all line strings in list into file output close(manual close (done for you when file is collectedoutput flush(flush output buffer to disk without closing anyfile seek(nchange file position to offset for next operation for line in open('data')use line file iterators read line by line open(' txt'encoding='latin- 'python unicode text files (str stringsopen(' bin''rb'python bytes files (bytes stringscodecs open(' txt'encoding='utf 'python unicode text files (unicode stringsopen(' bin''rb'python bytes files (str stringsopening files to open filea program calls the built-in open functionwith the external filename firstfollowed by processing mode the call returns file objectwhich in turn has methods for data transferafile open(filenamemodeafile method(the first argument to openthe external filenamemay include platform-specific and absolute or relative directory path prefix without directory paththe file is assumed to exist in the current working directory ( where the script runsas we'll see in ' expanded file coveragethe filename may also contain non-ascii unicode characters that python automatically translates to and from the underlying platform' encodingor be provided as pre-encoded byte string the second argument to openprocessing modeis typically the string 'rto open for text input (the default)'wto create and open for text outputor 'ato open for appending text to the end ( for adding to logfilesthe processing mode argument can specify additional optionsfiles
858
unicode encodings are turned offadding opens the file for both input and output ( you can both read and write to the same file objectoften in conjunction with seek operations to reposition in the fileboth of the first two arguments to open must be python strings an optional third argument can be used to control output buffering--passing zero means that output is unbuffered (it is transferred to the external file immediately on write method call)and additional arguments may be provided for special types of files ( an encoding for unicode text files in python xwe'll cover file fundamentals and explore some basic examples herebut we won' go into all file-processing mode optionsas usualconsult the python library manual for additional details using files once you make file object with openyou can call its methods to read from or write to the associated external file in all casesfile text takes the form of strings in python programsreading file returns its content in stringsand content is passed to the write methods as strings reading and writing methods come in multiple flavorstable - lists the most common here are few fundamental usage notesfile iterators are best for reading lines though the reading and writing methods in the table are commonkeep in mind that probably the best way to read lines from text file today is to not read the file at all--as we'll see in files also have an iterator that automatically reads one line at time in for looplist comprehensionor other iteration context content is stringsnot objects notice in table - that data read from file always comes back to your script as stringso you'll have to convert it to different type of python object if string is not what you need similarlyunlike with the print operationpython does not add any formatting and does not convert objects to strings automatically when you write data to file--you must send an already formatted string because of thisthe tools we have already met to convert objects to and from strings ( intfloatstrand the string formatting expression and methodcome in handy when dealing with files python also includes advanced standard library tools for handling generic object storage (the pickle module)for dealing with packed binary data in files (the struct module)and for processing special types of content such as jsonxmland csv text we'll see these at work later in this and bookbut python' manuals document them in full tuplesfilesand everything else
859
by defaultoutput files are always bufferedwhich means that text you write may not be transferred from memory to disk immediately--closing fileor running its flush methodforces the buffered data to disk you can avoid buffering with extra open argumentsbut it may impede performance python files are also randomaccess on byte offset basis--their seek method allows your scripts to jump around to read and write at specific locations close is often optionalauto-close on collection calling the file close method terminates your connection to the external filereleases its system resourcesand flushes its buffered output to disk if any is still in memory as discussed in in python an object' memory space is automatically reclaimed as soon as the object is no longer referenced anywhere in the program when file objects are reclaimedpython also automatically closes the files if they are still open (this also happens when program shuts downthis means you don' always need to manually close your files in standard pythonespecially those in simple scripts with short runtimesand temporary files used by single line or expression on the other handincluding manual close calls doesn' hurtand may be good habit to formespecially in long-running systems strictly speakingthis auto-closeon-collection feature of files is not part of the language definition--it may change over timemay not happen when you expect it to in interactive shellsand may not work the same in other python implementations whose garbage collectors may not reclaim and close files at the same points as standard cpython in factwhen many files are opened within loopspythons other than cpython may require close calls to free up system resources immediatelybefore garbage collection can get around to freeing objects moreoverclose calls may sometimes be required to flush buffered output of file objects not yet reclaimed for an alternative way to guarantee automatic file closesalso see this section' later discussion of the file object' context managerused with the with/as statement in python and files in action let' work through simple example that demonstrates file-processing basics the following code begins by opening new text file for outputwriting two lines (strings terminated with newline marker\ )and closing the file laterthe example opens the same file again in input mode and reads the lines back one at time with read line notice that the third readline call returns an empty stringthis is how python file methods tell you that you've reached the end of the file (empty lines in the file come back as strings containing just newline characternot as empty stringshere' the complete interactionmyfile open('myfile txt'' 'myfile write('hello text file\ ' open for text outputcreate/empty write line of textstring files
860
myfile close(myfile open('myfile txt'myfile readline('hello text file\nmyfile readline('goodbye text file\nmyfile readline('flush output buffers to disk open for text input'ris default read the lines back empty stringend-of-file notice that file write calls return the number of characters written in python xin they don'tso you won' see these numbers echoed interactively this example writes each line of textincluding its end-of-line terminator\nas stringwrite methods don' add the end-of-line character for usso we must include it to properly terminate our lines (otherwise the next write will simply extend the current line in the fileif you want to display the file' content with end-of-line characters interpretedread the entire file into string all at once with the file object' read method and print itopen('myfile txt'read('hello text file\ngoodbye text file\nread all at once into string print(open('myfile txt'read()hello text file goodbye text file user-friendly display and if you want to scan text file line by linefile iterators are often your best optionfor line in open('myfile txt')print(lineend=''hello text file goodbye text file use file iteratorsnot reads when coded this waythe temporary file object created by open will automatically read and return one line on each loop iteration this form is usually easiest to codegood on memory useand may be faster than some other options (depending on many variablesof coursesince we haven' reached statements or iterators yetthoughyou'll have to wait until for more complete explanation of this code windows usersas mentioned in open accepts unix-style forward slashes in place of backward slashes on windowsso any of the following forms work for directory paths--raw stringsforward slashesor doubled-up backslashesopen( ' :\python \lib\pdb py'readline('#/usr/bin/env python \nopen(' :/python /lib/pdb py'readline('#/usr/bin/env python \ tuplesfilesand everything else
861
'#/usr/bin/env python \nthe raw string form in the second command is still useful to turn off accidental escapes when you can' control string contentand in other contexts text and binary filesthe short story strictly speakingthe example in the prior section uses text files in both python and xfile type is determined by the second argument to openthe mode string--an included "bmeans binary python has always supported both text and binary filesbut in python there is sharper distinction between the twotext files represent content as normal str stringsperform unicode encoding and decoding automaticallyand perform end-of-line translation by default binary files represent content as special bytes string type and allow programs to access file content unaltered in contrastpython text files handle both -bit text and binary dataand special string type and file interface (unicode strings and codecs openhandles unicode text the differences in python stem from the fact that simple and unicode text have been merged in the normal string type--which makes sensegiven that all text is unicodeincluding ascii and other -bit encodings because most programmers deal only with ascii textthey can get by with the basic text file interface used in the prior exampleand normal strings all strings are technically unicode in xbut ascii users will not generally notice in facttext files and strings work the same in and if your script' scope is limited to such simple forms of text if you need to handle internationalized applications or byte-oriented datathoughthe distinction in impacts your code (usually for the betterin generalyou must use bytes strings for binary filesand normal str strings for text files moreoverbecause text files implement unicode encodingsyou should not open binary data file in text mode--decoding its content to unicode text will likely fail let' look at an example when you read binary data file you get back bytes object -- sequence of small integers that represent absolute byte values (which may or may not correspond to characters)which looks and feels almost exactly like normal string in python xand assuming an existing binary filedata open('data bin''rb'read(data '\ \ \ \ spam\ \ data[ : 'spamdata[ : ][ open binary filerb=read binary bytes string holds binary data act like strings but really are small -bit integers files
862
' python / bin(function in additionbinary files do not perform any end-of-line translation on datatext files by default map all forms to and from \ when written and read and implement unicode encodings on transfers in binary files like this one work the same in python xbut byte strings are simply normal strings and have no leading when displayedand text files must use the codecs module to add unicode processing per the note at the start of this thoughthat' as much as we're going to say about unicode text and binary data files hereand just enough to understand upcoming examples in this since the distinction is of marginal interest to many python programmerswe'll defer to the files preview in for quick tour and postpone the full story until for nowlet' move on to some more substantial file examples to demonstrate few common use cases storing python objects in filesconversions our next example writes variety of python objects into text file on multiple lines notice that it must convert objects to strings using conversion tools againfile data is always strings in our scriptsand write methods do not do any automatic to-string formatting for us (for spacei' omitting byte-count return values from write methods from here on)xyz 'spamd {' ' ' ' [ open('datafile txt'' ' write( '\ ' write('% ,% ,% \ (xyz) write(str( '$str( '\ ' close(native python objects must be strings to store in file create output text file terminate lines with \ convert numbers to strings convert and separate with once we have created our filewe can inspect its contents by opening it and reading it into string (strung together as single operation herenotice that the interactive echo gives the exact byte contentswhile the print operation interprets embedded endof-line characters to render more user-friendly displaychars open('datafile txt'read(raw string display chars "spam\ , , \ [ ]${' ' ' ' }\nprint(charsuser-friendly display spam , , [ ]${' ' ' ' we now have to use other conversion tools to translate from the strings in the text file to real python objects as python never converts strings to numbers (or other types of tuplesfilesand everything else
863
like indexingadditionand so onf open('datafile txt'line readline(line 'spam\nline rstrip('spamopen again read one line remove end-of-line for this first linewe used the string rstrip method to get rid of the trailing end-of-line charactera line[:- slice would worktoobut only if we can be sure all lines end in the \ character (the last line in file sometimes does notso farwe've read the line containing the string now let' grab the next linewhich contains numbersand parse out (that isextractthe objects on that lineline readline(line ' , , \nparts line split(','parts [' '' '' \ 'next line from file it' string here split (parseon commas we used the string split method here to chop up the line on its comma delimitersthe result is list of substrings containing the individual numbers we still must convert from strings to integersthoughif we wish to perform math on theseint(parts[ ] numbers [int(pfor in partsnumbers [ convert from string to int convert all in list at once as we have learnedint translates string of digits into an integer objectand the list comprehension expression introduced in can apply the call to each item in our list all at once (you'll find more on list comprehensions later in this booknotice that we didn' have to run rstrip to delete the \ at the end of the last partint and some other converters quietly ignore whitespace around digits finallyto convert the stored list and dictionary in the third line of the filewe can run them through evala built-in function that treats string as piece of executable program code (technicallya string containing python expression)line readline(line "[ ]${' ' ' ' }\nparts line split('$'parts ['[ ]'"{' ' ' ' }\ "eval(parts[ ][ objects [eval(pfor in partssplit (parseon convert to any object type do same for all in list files
864
[[ ]{' ' ' ' }because the end result of all this parsing and converting is list of normal python objects instead of stringswe can now apply list and dictionary operations to them in our script storing native python objectspickle using eval to convert from strings to objectsas demonstrated in the preceding codeis powerful tool in factsometimes it' too powerful eval will happily run any python expression--even one that might delete all the files on your computergiven the necessary permissionsif you really want to store native python objectsbut you can' trust the source of the data in the filepython' standard library pickle module is ideal the pickle module is more advanced tool that allows us to store almost any python object in file directlywith no toor from-string conversion requirement on our part it' like super-general data formatting and parsing utility to store dictionary in filefor instancewe pickle it directlyd {' ' ' ' open('datafile pkl''wb'import pickle pickle dump(dff close(pickle any object to file thento get the dictionary back laterwe simply use pickle again to re-create itf open('datafile pkl''rb' pickle load(fe {' ' ' ' load any object from file we get back an equivalent dictionary objectwith no manual splitting or converting required the pickle module performs what is known as object serialization--converting objects to and from strings of bytes--but requires very little work on our part in factpickle internally translates our dictionary to string formthough it' not much to look at (and may vary if we pickle in other data protocol modes)open('datafile pkl''rb'read(format is prone to changeb'\ \ } \ ( \ \ \ \ bq\ \ \ \ \ \ aq\ \ because pickle can reconstruct the object from this formatwe don' have to deal with it ourselves for more on the pickle modulesee the python standard library manualor import pickle and pass it to help interactively while you're exploringalso take look at the shelve module shelve is tool that uses pickle to store python objects in an access-by-key filesystemwhich is beyond our scope here (though you will get to see an example of shelve in action in and other pickle examples in and tuplesfilesand everything else
865
modebinary mode is always required in python xbecause the pickler creates and uses bytes string objectand these objects imply binarymode files (text-mode files imply str strings in xin earlier pythons it' ok to use text-mode files for protocol (the defaultwhich creates ascii text)as long as text mode is used consistentlyhigher protocols require binary-mode files python ' default protocol is (binary)but it creates bytes even for protocol see and python' library manualor reference books for more details on and examples of pickled data python also has cpickle modulewhich is an optimized version of pickle that can be imported directly for speed python renames this module _pickle and uses it automatically in pickle--scripts simply import pickle and let python optimize itself storing python objects in json format the prior section' pickle module translates nearly arbitrary python objects to proprietary format developed specifically for pythonand honed for performance over many years json is newer and emerging data interchange formatwhich is both programming-language-neutral and supported by variety of systems mongodbfor instancestores data in json document database (using binary json formatjson does not support as broad range of python object types as picklebut its portability is an advantage in some contextsand it represents another way to serialize specific category of python objects for storage and transmission moreoverbecause json is so close to python dictionaries and lists in syntaxthe translation to and from python objects is trivialand is automated by the json standard library module for examplea python dictionary with nested structures is very similar to json datathough python' variables and expressions support richer structuring options (any part of the following can be an arbitrary expression in python code)name dict(first='bob'last='smith'rec dict(name=namejob=['dev''mgr']age= rec {'job'['dev''mgr']'name'{'last''smith''first''bob'}'age' the final dictionary format displayed here is valid literal in python codeand almost passes for json when printed as isbut the json module makes the translation official --here translating python objects to and from json serialized string representation in memoryimport json json dumps(rec'{"job"["dev""mgr"]"name"{"last""smith""first""bob"}"age" } json dumps(recs files
866
'{"job"["dev""mgr"]"name"{"last""smith""first""bob"}"age" } json loads(so {'job'['dev''mgr']'name'{'last''smith''first''bob'}'age' =rec true it' similarly straightforward to translate python objects to and from json data strings in files prior to being stored in fileyour data is simply python objectsthe json module recreates them from the json textual representation when it loads it from the filejson dump(recfp=open('testjson txt'' ')indent= print(open('testjson txt'read()"job""dev""mgr]"name""last""smith""first""bob}"age" json load(open('testjson txt') {'job'['dev''mgr']'name'{'last''smith''first''bob'}'age' once you've translated from json textyou process the data using normal python object operations in your script for more details on json-related topicssee python' library manuals and search the web note that strings are all unicode in json to support text drawn from international character setsso you'll see leading on strings after translating from json data in python (but not in )this is just the syntax of unicode objects in xas introduced and and covered in full in because unicode text strings support all the usual string operationsthe difference is negligible to your code while text resides in memorythe distinction matters most when transferring text to and from filesand then usually only for non-ascii types of text where encodings come into play there is also support in the python world for translating objects to and from xmla text format used in see the web for details for another semirelated tool that deals with formatted data filessee the standard library' csv module it parses and creates csv (comma-separated valuedata in files and strings this doesn' map as directly to python objectsbut is another common data exchange formatimport csv rdr csv reader(open('csvdata txt') tuplesfilesand everything else
867
[' ''bbb''cc''dddd'[' '' '' '' 'storing packed binary datastruct one other file-related note before we move onsome advanced applications also need to deal with packed binary datacreated perhaps by language program or network connection python' standard library includes tool to help in this domain--the struct module knows how to both compose and parse packed binary data in sensethis is another data-conversion tool that interprets strings in files as binary data we saw an overview of this tool in but let' take another quick look here for more perspective to create packed binary data fileopen it in 'wb(write binarymodeand pass struct format string and some python objects the format string used here means pack as -byte integera -character string (which must be bytes string as of python )and -byte integerall in big-endian form (other format codes handle padding bytesfloating-point numbersand more) open('data bin''wb'import struct data struct pack('> sh' 'spam' data '\ \ \ \ spam\ \ write(dataf close(open binary output file make packed binary data write byte string python creates binary bytes data stringwhich we write out to the file normally--this one consists mostly of nonprintable characters printed in hexadecimal escapesand is the same binary file we met earlier to parse the values out to normal python objectswe simply read the string back and unpack it using the same format string python extracts the values into normal python objects--integers and stringf open('data bin''rb'data read(data '\ \ \ \ spam\ \ values struct unpack('> sh'datavalues ( 'spam' get packed binary data convert to python objects binary data files are advanced and somewhat low-level tools that we won' cover in more detail herefor more helpsee the struct coverage in consult the python library manualor import struct and pass it to the help function interactively also note that you can use the binary file-processing modes 'wband 'rbto process simpler binary filesuch as an image or audio fileas whole without having to unpack its contentsin such cases your code might pass it unparsed to other files or tools files
868
you'll also want to watch for ' discussion of the file' context manager supportnew as of python and though more feature of exception processing than files themselvesit allows us to wrap file-processing code in logic layer that ensures that the file will be closed (and if neededhave its output flushed to diskautomatically on exitinstead of relying on the auto-close during garbage collectionwith open( ' :\code\data txt'as myfilefor line in myfileuse line here see for details the try/finally statement that we'll also study in can provide similar functionalitybut at some cost in extra code--three extra linesto be precise (though we can often avoid both options and let python close files for us automatically)myfile open( ' :\code\data txt'tryfor line in myfileuse line here finallymyfile close(the with context manager scheme ensures release of system resources in all pythonsand may be more useful for output files to guarantee buffer flushesunlike the more general trythoughit is also limited to objects that support its protocol since both these options require more information than we have yet obtainedhoweverwe'll postpone details until later in this book other file tools there are additionalmore specialized file methods shown in table - and even more that are not in the table for instanceas mentioned earlierseek resets your current position in file (the next read or write happens at that position)flush forces buffered output to be written out to disk without closing the connection (by defaultfiles are always buffered)and so on the python standard library manual and the reference books described in the preface provide complete lists of file methodsfor quick lookrun dir or help call interactivelypassing in an open file object (in python but not xyou can pass in the name file insteadfor more file-processing exampleswatch for the sidebar "why you will carefile scannerson page in it sketches common filescanning loop code patterns with statements we have not covered enough yet to use here alsonote that although the open function and the file objects it returns are your main interface to external files in python scriptthere are additional file-like tools in the python toolset among these tuplesfilesand everything else
869
preopened file objects in the sys modulesuch as sys stdout (see "print operationson page in for detailsdescriptor files in the os module integer file handles that support lower-level tools such as file locking (see also the "xmode in python ' open for exclusive creationsocketspipesand fifos file-like objects used to synchronize processes or communicate over networks access-by-key files known as "shelvesused to store unaltered and pickled python objects directlyby key (used in shell command streams tools such as os popen and subprocess popen that support spawning shell commands and reading and writing to their standard streams (see and for examplesthe third-party open source domain offers even more file-like toolsincluding support for communicating with serial ports in the pyserial extension and interactive programs in the pexpect system see applications-focused python texts and the web at large for additional information on file-like tools version skew notein python xthe built-in name open is essentially synonym for the name fileand you may technically open files by calling either open or file (though open is generally preferred for openingin python xthe name file is no longer availablebecause of its redundancy with open python users may also use the name file as the file object typein order to customize files with object-oriented programming (described later in this bookin python xfiles have changed radically the classes used to implement file objects live in the standard library module io see this module' documentation or code for the classes it makes available for customizationand run type(fcall on an open file for hints core types review and summary now that we've seen all of python' core built-in types in actionlet' wrap up our object types tour by reviewing some of the properties they share table - classifies all the major types we've seen so far according to the type categories introduced earlier here are some points to remembercore types review and summary
870
--stringslistsand tuples--all share sequence operations such as concatenationlengthand indexing only mutable objects--listsdictionariesand sets--may be changed in placeyou cannot change numbersstringsor tuples in place files export only methodsso mutability doesn' really apply to them--their state may be changed when they are processedbut this isn' quite the same as python core type mutability constraints "numbersin table - includes all number typesinteger (and the distinct long integer in )floating pointcomplexdecimaland fraction "stringsin table - includes stras well as bytes in and unicode in xthe bytearray string type in and is mutable sets are something like the keys of valueless dictionarybut they don' map to values and are not orderedso sets are neither mapping nor sequence typefrozenset is an immutable variant of set in addition to type category operationsas of python and all the types in table - have callable methodswhich are generally specific to their type table - object classifications object type category mutablenumbers (allnumeric no strings (allsequence no lists sequence yes dictionaries mapping yes tuples sequence no files extension / sets set yes frozenset set no bytearray sequence yes why you will careoperator overloading in part vi of this bookwe'll see that objects we implement with classes can pick and choose from these categories arbitrarily for instanceif we want to provide new kind of specialized sequence object that is consistent with built-in sequenceswe can code class that overloads things like indexing and concatenationclass mysequencedef __getitem__(selfindex)called on self[index]others def __add__(selfother)called on self other tuplesfilesand everything else
871
preferred in iterations and so on we can also make the new object mutable or not by selectively implementing methods called for in-place change operations ( __setitem__ is called on self[index]=value assignmentsalthough it' beyond this book' scopeit' also possible to implement new objects in an external language like as extension types for thesewe fill in function pointer slots to choose between numbersequenceand mapping operation sets object flexibility this part of the book introduced number of compound object types--collections with components in generallistsdictionariesand tuples can hold any kind of object sets can contain any type of immutable object listsdictionariesand tuples can be arbitrarily nested listsdictionariesand sets can dynamically grow and shrink because they support arbitrary structurespython' compound object types are good at representing complex information in programs for examplevalues in dictionaries may be listswhich may contain tupleswhich may contain dictionariesand so on the nesting can be as deep as needed to model the data to be processed let' look at an example of nesting the following interaction defines tree of nested compound sequence objectsshown in figure - to access its componentsyou may include as many index operations as required python evaluates the indexes from left to rightand fetches reference to more deeply nested object at each step figure - may be pathologically complicated data structurebut it illustrates the syntax used to access nested objects in generall ['abc'[( )([ ] )] [ [( )([ ] ) [ ][ ([ ] [ ][ ][ [ [ ][ ][ ][ references versus copies mentioned that assignments always store references to objectsnot copies of those objects in practicethis is usually what you want because assignments can generate multiple references to the same objectthoughit' important to be aware that core types review and summary
872
expression ['abc'[( )([ ] )] syntactically nested objects are internally represented as references ( pointersto separate pieces of memory changing mutable object in place may affect other references to the same object elsewhere in your program if you don' want such behavioryou'll need to tell python to copy the object explicitly we studied this phenomenon in but it can become more subtle when larger objects of the sort we've explored since then come into play for instancethe following example creates list assigned to xand another list assigned to that embeds reference back to list it also creates dictionary that contains another reference back to list xx [ [' ' ' ' {' ': ' ': embed references to ' object at this pointthere are three references to the first list createdfrom the name xfrom inside the list assigned to land from inside the dictionary assigned to the situation is illustrated in figure - because lists are mutablechanging the shared list object from any of the three references also changes what the other two referencex[ 'surprisechanges all three referencesl [' '[ 'surprise' ]' ' {' '[ 'surprise' ]' ' references are higher-level analog of pointers in other languages that are always followed when used although you can' grab hold of the reference itselfit' possible to tuplesfilesand everything else
873
within the objects referenced by and dchanging the shared list from makes it look different from and dtoo store the same reference in more than one place (variableslistsand so onthis is feature--you can pass large object around program without generating expensive copies of it along the way if you really do want copieshoweveryou can request themslice expressions with empty limits ( [:]copy sequences the dictionarysetand list copy method ( copy()copies dictionarysetor list (the list' copy is new as of some built-in functionssuch as list and dict make copies (list( )dict( )set( )the copy standard library module makes full copies when needed for examplesay you have list and dictionaryand you don' want their values to be changed through other variablesl [ , , {' ': ' ': to prevent thissimply assign copies to the other variablesnot references to the same objectsa [: copy(instead of (or list( )instead of (ditto for setsthis waychanges made from the other variables will change the copiesnot the originalsa[ 'nib[' ''spamld ([ ]{' ' ' ' }core types review and summary
874
([ 'ni' ]{' ' ' ''spam'' ' }in terms of our original exampleyou can avoid the reference side effects by slicing the original list instead of simply naming itx [ [' ' [:]' ' {' ': [:]' ': embed copies of ' object this changes the picture in figure - -- and will now point to different lists than the net effect is that changes made through will impact only xnot and dsimilarlychanges to or will not impact one final note on copiesempty-limit slices and the dictionary copy method only make top-level copiesthat isthey do not copy nested data structuresif any are present if you need completefully independent copy of deeply nested data structure (like the various record structures we've coded in recent )use the standard copy moduleintroduced in import copy copy deepcopy(yfully copy an arbitrarily nested object this call recursively traverses objects to copy all their parts this is much more rare casethoughwhich is why you have to say more to use this scheme references are usually what you will wantwhen they are notslices and copy methods are usually as much copying as you'll need to do comparisonsequalityand truth all python objects also respond to comparisonstests for equalityrelative magnitudeand so on python comparisons always inspect all parts of compound objects until result can be determined in factwhen nested objects are presentpython automatically traverses data structures to apply comparisons from left to rightand as deeply as needed the first difference found along the way determines the comparison result this is sometimes called recursive comparison--the same comparison requested on the top-level objects is applied to each of the nested objectsand to each of their nested objectsand so onuntil result is found later in this book--in --we'll see how to write recursive functions of our own that work similarly on nested structures for nowthink about comparing all the linked pages at two websites if you want metaphor for such structuresand reason for writing recursive functions to process them in terms of core typesthe recursion is automatic for instancea comparison of list objects compares all their components automatically until mismatch is found or the end is reachedl [ (' ' ) [ (' ' )same valueunique objects tuplesfilesand everything else
875
(truefalseequivalentsame objectherel and are assigned lists that are equivalent but distinct objects as review of what we saw in because of the nature of python referencesthere are two ways to test for equalitythe =operator tests value equivalence python performs an equivalence testcomparing all nested objects recursively the is operator tests object identity python tests whether the two are really the same object ( live at the same address in memoryin the preceding examplel and pass the =test (they have equivalent values because all their components are equivalentbut fail the is check (they reference two different objectsand hence two different pieces of memorynotice what happens for short stringsthoughs 'spams 'spams = is (truetrueherewe should again have two distinct objects that happen to have the same value=should be trueand is should be false but because python internally caches and reuses some strings as an optimizationthere really is just single string 'spamin memoryshared by and hencethe is identity test reports true result to trigger the normal behaviorwe need to use longer stringss ' longer strings ' longer strings = is (truefalseof coursebecause strings are immutablethe object caching mechanism is irrelevant to your code--strings can' be changed in placeregardless of how many variables refer to them if identity tests seem confusingsee for refresher on object reference concepts as rule of thumbthe =operator is what you will want to use for almost all equality checksis is reserved for highly specialized roles we'll see cases later in the book where both operators are put to use relative magnitude comparisons are also applied recursively to nested data structuresl [ (' ' ) [ (' ' ) (falsefalsetruelessequalgreatertuple of results herel is greater than because the nested is greater than by now you should know that the result of the last line is really tuple of three objects--the results of the three expressions typed (an example of tuple without its enclosing parenthesescore types review and summary
876
numbers are compared by relative magnitudeafter conversion to the common highest type if needed strings are compared lexicographically (by the character set code point values returned by ord)and character by character until the end or first mismatch ("abc"ac"lists and tuples are compared by comparing each component from left to rightand recursively for nested structuresuntil the end or first mismatch ([ [ ]sets are equal if both contain the same items (formallyif each is subset of the other)and set relative magnitude comparisons apply subset and superset tests dictionaries compare as equal if their sorted (keyvaluelists are equal relative magnitude comparisons are not supported for dictionaries in python xbut they work in as though comparing sorted (keyvaluelists nonnumeric mixed-type magnitude comparisons ( 'spam'are errors in python they are allowed in python xbut use fixed but arbitrary ordering rule based on type name string by proxythis also applies to sortswhich use comparisons internallynonnumeric mixed-type collections cannot be sorted in in generalcomparisons of structured objects proceed as though you had written the objects as literals and compared all their parts one at time from left to right in later we'll see other object types that can change the way they get compared python and mixed-type comparisons and sorts per the last point in the preceding section' listthe change in python for nonnumeric mixed-type comparisons applies to magnitude testsnot equalitybut it also applies by proxy to sortingwhich does magnitude testing internally in python these all workthough mixed types compare by an arbitrary orderingc:\codec:\python \python =' false >' false [' '' 'sort([ ' 'sort(equality does not convert non-numbers compares by type name stringintstr ditto for sorts but python disallows mixed-type magnitude testingexcept numeric types and manually converted typesc:\codec:\python \python =' xequality works but magnitude does not false >' typeerrorunorderable typesint(str( tuplesfilesand everything else
877
ditto for sorts [ ' 'sort(typeerrorunorderable typesstr(int( true str( >' ' >int(' '(truetruemixed numbers convert to highest type manual conversions force the issue python and dictionary comparisons the second-to-last point in the preceding section also merits illustration in python xdictionaries support magnitude comparisonsas though you were comparing sorted key/value listsc:\codec:\python \python {' ': ' ': {' ': ' ': = false true dictionary equality dictionary magnitude only as noted briefly in thoughmagnitude comparisons for dictionaries are removed in python because they incur too much overhead when equality is desired (equality uses an optimized scheme in that doesn' literally compare sorted keyvalue lists) :\codec:\python \python {' ': ' ': {' ': ' ': = false typeerrorunorderable typesdict(dict(the alternative in is to either write loops to compare values by keyor compare the sorted key/value lists manually--the items dictionary methods and sorted built-in sufficelist( items()[(' ' )(' ' )sorted( items()[(' ' )(' ' )sorted( items()sorted( items()true sorted( items()sorted( items()false magnitude test in this takes more codebut in practicemost programs requiring this behavior will develop more efficient ways to compare data in dictionaries than either this workaround or the original behavior in python core types review and summary
878
notice that the test results returned in the last two examples represent true and false values they print as the words true and falsebut now that we're using logical tests like these in earnesti should be bit more formal about what these names really mean in pythonas in most programming languagesan integer represents falseand an integer represents true in additionthoughpython recognizes any empty data structure as false and any nonempty data structure as true more generallythe notions of true and false are intrinsic properties of every object in python--each object is either true or falseas followsnumbers are false if zeroand true otherwise other objects are false if emptyand true otherwise table - gives examples of true and false values of objects in python table - example object truth values object value "spamtrue "false [ true [false {' ' true {false true false none false as one applicationbecause objects are true or false themselvesit' common to see python programmers code tests like if :whichassuming is stringis the same as if !''in other wordsyou can test the object itself to see if it contains anythinginstead of comparing it to an emptyand therefore falseobject of the same type (more on if statements in the next the none object as shown in the last row in table - python also provides special object called nonewhich is always considered to be false none was introduced briefly in it is the only value of special data type in python and typically serves as an empty placeholder (much like null pointer in cfor examplerecall that for lists you cannot assign to an offset unless that offset already exists--the list does not magically grow if you attempt an out-of-bounds assignment tuplesfilesand everything else
879
fill it with none objectsl [none [nonenonenonenonenonenonenonethis doesn' limit the size of the list (it can still grow and shrink later)but simply presets an initial size to allow for future index assignments you could initialize list with zeros the same wayof coursebut best practice dictates using none if the type of the list' contents is variable or not yet known keep in mind that none does not mean "undefined that isnone is somethingnot nothing (despite its name!)--it is real object and real piece of memory that is created and given built-in name by python itself watch for other uses of this special object later in the bookas we'll learn in part ivit is also the default return value of functions that don' exit by running into return statement with result value the bool type while we're on the topic of truthalso keep in mind that the python boolean type boolintroduced in simply augments the notions of true and false in python as we learned in the built-in words true and false are just customized versions of the integers and --it' as if these two words have been preassigned to and everywhere in python because of the way this new type is implementedthis is really just minor extension to the notions of true and false already describeddesigned to make truth values more explicitwhen used explicitly in truth test codethe words true and false are equivalent to and but they make the programmer' intent clearer results of boolean tests run interactively print as the words true and falseinstead of as and to make the type of result clearer you are not required to use only boolean types in logical statements such as ifall objects are still inherently true or falseand all the boolean concepts mentioned in this still work as described if you use other types python also provides bool builtin function that can be used to test the boolean value of an object if you want to make this explicit ( whether it is true--that isnonzero or nonempty)bool( true bool('spam'true bool({}false in practicethoughyou'll rarely notice the boolean type produced by logic testsbecause boolean results are used automatically by if statements and other selection tools we'll explore booleans further when we study logical statements in core types review and summary
880
as summary and referencefigure - sketches all the built-in object types available in python and their relationships we've looked at the most prominent of thesemost of the other kinds of objects in figure - correspond to program units ( functions and modulesor exposed interpreter internals ( stack frames and compiled codethe largest point to notice here is that everything in python system is an object type and may be processed by your python programs for instanceyou can pass class to functionassign it to variablestuff it in list or dictionaryand so on type objects in facteven types themselves are an object type in pythonthe type of an object is an object of type type (say that three times fast!seriouslya call to the built-in function type(xreturns the type object of object the practical application of this is that type objects can be used for manual type comparisons in python if statements howeverfor reasons introduced in manual type testing is usually not the right thing to do in pythonsince it limits your code' flexibility one note on type namesas of python each core type has new built-in name added to support type customization through object-oriented subclassingdictliststrtupleintfloatcomplexbytestypesetand more in python names all references classesand in python but not xfile is also type name and synonym for open calls to these names are really object constructor callsnot simply conversion functionsthough you can treat them as simple functions for basic usage in additionthe types standard library module in python provides additional type names for types that are not available as built-ins ( the type of functionin python but not xthis module also includes synonyms for built-in type names)and it is possible to do type tests with the isinstance function for exampleall of the following type tests are truetype([ ]=type([]type([ ]=list isinstance([ ]listcompare to type of another list compare to list type name test if list or customization thereof import types def ()pass type( =types functiontype types has names for other types because types can be subclassed in python todaythe isinstance technique is generally recommended see for more on subclassing built-in types in python and later tuplesfilesand everything else
881
in pythoneven the type of an objectsome extension typessuch as named tuplesmight belong in this figure toobut the criteria for inclusion in the core types set are not formal core types review and summary
882
general apply to instances of user-defined classes in shortin python and for new-style classes in python xthe type of class instance is the class from which the instance was made for classic classes in python xall class instances are instead of the type "instance,and we must compare instance __class__ attributes to compare their types meaningfully since we're not yet equipped to tackle the subject of classeswe'll postpone the rest of this story until other types in python besides the core objects studied in this part of the bookand the program-unit objects such as functionsmodulesand classes that we'll meet latera typical python installation has dozens of additional object types available as linked-in extensions or python classes--regular expression objectsdbm filesgui widgetsnetwork socketsand so on depending on whom you askthe named tuple we met earlier in this may fall in this category too (decimal and fraction of tend to be more ambiguousthe main difference between these extra tools and the built-in types we've seen so far is that the built-ins provide special language creation syntax for their objects ( for an integer[ , for listthe open function for filesand def and lambda for functionsother tools are generally made available in standard library modules that you must first import to useand aren' usually considered core types for instanceto make regular expression objectyou import re and call re compile(see python' library reference for comprehensive guide to all the tools available to python programs built-in type gotchas that' the end of our look at core data types we'll wrap up this part of the book with discussion of common problems that seem to trap new users (and the occasional expert)along with their solutions some of this is review of ideas we've already coveredbut these issues are important enough to warn about again here assignment creates referencesnot copies because this is such central concepti'll mention it againshared references to mutable objects in your program can matter for instancein the following examplethe list object assigned to the name is referenced both from and from inside the list assigned to the name changing in place changes what referencestool [ [' ' ' ' [' '[ ]' 'embed reference to tuplesfilesand everything else
883
[' '[ ]' 'changes too this effect usually becomes important only in larger programsand shared references are often exactly what you want if objects change out from under you in unwanted waysyou can avoid sharing objects by copying them explicitly for listsyou can always make top-level copy by using an empty-limits sliceamong other techniques described earlierl [ [' ' [:]' ' [ [ [' '[ ]' 'embed copy of (or list( )or copy()changes only lnot rememberslice limits default to and the length of the sequence being slicedif both are omittedthe slice extracts every item in the sequence and so makes top-level copy ( newunshared objectrepetition adds one level deep repeating sequence is like adding it to itself number of times howeverwhen mutable sequences are nestedthe effect might not always be what you expect for instancein the following example is assigned to repeated four timeswhereas is assigned to list containing repeated four timesl [ [ like [ [ [ [ [llx [ [[ ][ ][ ][ ]because was nested in the second repetitiony winds up embedding references back to the original list assigned to land so is open to the same sorts of side effects noted in the preceding sectionl[ impacts but not [ [[ ][ ][ ][ ]this may seem artificial and academic--until it happens unexpectedly in your codethe same solutions to this problem apply here as in the previous sectionas this is really just another way to create the shared mutable object reference case--make copies when you don' want shared referencesbuilt-in type gotchas
884
[list( ) embed (sharedcopy of [ [[ ][ ][ ][ ]even more subtlyalthough doesn' share an object with anymoreit still embeds four references to the same copy of it if you must avoid that sharing tooyou'll want to make sure each embedded copy is uniquey[ ][ all four copies are still the same [[ ][ ][ ][ ] [ [list(lfor in range( ) [[ ][ ][ ][ ] [ ][ [[ ][ ][ ][ ]if you remember that repetitionconcatenationand slicing copy only the top level of their operand objectsthese sorts of cases make much more sense beware of cyclic data structures we actually encountered this concept in prior exerciseif collection object contains reference to itselfit' called cyclic object python prints whenever it detects cycle in the objectrather than getting stuck in an infinite loop (as it once did long ago) ['grail' append(ll ['grail']append reference to same object generates cycle in objectbesides understanding that the three dots in square brackets represent cycle in the objectthis case is worth knowing about because it can lead to gotchas--cyclic structures may cause code of your own to fall into unexpected loops if you don' anticipate them for instancesome programs that walk through structured data must keep listdictionaryor set of already visited itemsand check it when they're about to step into cycle that could cause an unwanted loop see the solutions to the "test your knowledgepart exerciseson page in appendix for more on this problem also watch for general discussion of recursion in as well as the reloadall py program in and the listtree class in for concrete examples of programs where cycle detection can matter the solution is knowledgedon' use cyclic references unless you really need toand make sure you anticipate them in programs that must care there are good reasons to tuplesfilesand everything else
885
reference themselves may be more surprise than asset immutable types can' be changed in place and once more for completenessyou can' change an immutable object in place insteadyou construct new object with slicingconcatenationand so onand assign it back to the original referenceif neededt ( [ errort [: ( ,ok( that might seem like extra coding workbut the upside is that the previous gotchas in this section can' happen when you're using immutable objects such as tuples and stringsbecause they can' be changed in placethey are not open to the sorts of side effects that lists are summary this explored the last two major core object types--the tuple and the file we learned that tuples support all the usual sequence operationshave just few methodsdo not allow any in-place changes because they are immutableand are extended by the named tuple type we also learned that files are returned by the built-in open function and provide methods for reading and writing data along the way we explored how to translate python objects to and from strings for storing in filesand we looked at the picklejsonand struct modules for advanced roles (object serialization and binary datafinallywe wrapped up by reviewing some properties common to all object types ( shared referencesand went through list of common mistakes ("gotchas"in the object type domain in the next part of this bookwe'll shift gearsturning to the topic of statement syntax-the way you code processing logic in your scripts along the waythis next part explores all of python' basic procedural statements the next kicks off this topic with an introduction to python' general syntax modelwhich is applicable to all statement types before moving onthoughtake the quizand then work through the end-of-part lab exercises to review type concepts statements largely just create and process objectsso make sure you've mastered this domain by working through all the exercises before reading on test your knowledgequiz how can you determine how large tuple iswhy is this tool located where it istest your knowledgequiz
886
write an expression that changes the first item in tuple ( should become ( in the process what is the default for the processing mode argument in file open call what module might you use to store python objects in file without converting them to strings yourself how might you go about copying all parts of nested structure at once when does python consider an object true what is your questtest your knowledgeanswers the built-in len function returns the length (number of contained itemsfor any container object in pythonincluding tuples it is built-in function instead of type method because it applies to many different types of objects in generalbuiltin functions and expressions may span many object typesmethods are specific to single object typethough some may be available on more than one type (indexfor exampleworks on lists and tuples because they are immutableyou can' really change tuples in placebut you can generate new tuple with the desired value given ( )you can change the first item by making new tuple from its parts by slicing and concatenatingt ( , [ :(recall that single-item tuples require trailing comma you could also convert the tuple to listchange it in placeand convert it back to tuplebut this is more expensive and is rarely required in practice--simply use list if you know that the object will require in-place changes the default for the processing mode argument in file open call is ' 'for reading text input for input text filessimply pass in the external file' name the pickle module can be used to store python objects in file without explicitly converting them to strings the struct module is relatedbut it assumes the data is to be in packed binary format in the filejson similarly converts limited set of python objects to and from strings per the json format import the copy moduleand call copy deepcopy(xif you need to copy all parts of nested structure this is also rarely seen in practicereferences are usually the desired behaviorand shallow copies ( alist[:]adict copy()set(aset)usually suffice for most copies an object is considered true if it is either nonzero number or nonempty collection object the built-in words true and false are essentially predefined to have the same meanings as integer and respectively acceptable answers include "to learn python,"to move on to the next part of the book,or "to seek the holy grail tuplesfilesand everything else
887
this session asks you to get your feet wet with built-in object fundamentals as beforea few new ideas may pop up along the wayso be sure to flip to the answers in appendix when you're done (or even when you're notif you have limited timei suggest starting with exercises and (the most practical of the bunch)and then working from first to last as time allows this is all fundamental materialso try to do as many of these as you canprogramming is hands-on activityand there is no substitute for practicing what you've read to make ideas gel the basics experiment interactively with the common type operations found in the various operation tables in this part of the book to get startedbring up the python interactive interpretertype each of the following expressionsand try to explain what' happening in each case note that the semicolon in some of these is being used as statement separatorto squeeze multiple statements onto single linefor examplex= ; assigns and then prints variable (more on statement syntax in the next part of the bookalso remember that comma between expressions usually builds tupleeven if there are no enclosing parenthesesx, , is three-item tuplewhich python prints back to you in parentheses * "spam"eggss "ham"eggs [: "green % and % ("eggs" 'green { and { }format('eggs' (' ',)[ (' '' ')[ [ , , [ , , ll[:] [: ] [- ] [- :([ , , [ , , ])[ : [ [ ] [ ] reverse() sort() index( {' ': ' ': }[' ' {' ': ' ': ' ': [' ' [' ' [' ' [( , , ) list( keys())list( values())( , , in [[]]["",[],(),{},nonetest your knowledgepart ii exercises
888
four strings or numbers ( =[ , , , ]thenexperiment with the following boundary cases you may never see these cases in real programs (especially not in the bizarre ways they appear here!)but they are intended to make you think about the underlying modeland some may be useful in less artificial forms--slicing out of bounds can helpfor exampleif sequence is as long as you expecta what happens when you try to index out of bounds ( [ ]) what about slicing out of bounds ( [- : ]) finallyhow does python handle it if you try to extract sequence in reversewith the lower bound greater than the higher bound ( [ : ])hinttry assigning to this slice ( [ : ]=['?'])and see where the value is put do you think this may be the same phenomenon you saw when slicing out of bounds indexingslicingand del define another list with four itemsand assign an empty list to one of its offsets ( [ ]=[]what happensthenassign an empty list to slice ( [ : ]=[]what happens nowrecall that slice assignment deletes the slice and inserts the new value where it used to be the del statement deletes offsetskeysattributesand names use it on your list to delete an item ( del [ ]what happens if you delete an entire slice (del [ :])what happens when you assign nonsequence to slice ( [ : ]= ) tuple assignment type the following linesx 'spamy 'eggsxy yx what do you think is happening to and when you type this sequence dictionary keys consider the following code fragmentsd { [ 'ad[ 'byou've learned that dictionaries aren' accessed by offsetsso what' going on heredoes the following shed any light on the subject(hintstringsintegersand tuples share which type category? [( )'cd { ' ' ' '( )' ' dictionary indexing create dictionary named with three entriesfor keys ' '' 'and 'cwhat happens if you try to index nonexistent key ( [' '])what does python do if you try to assign to nonexistent key ' ( [' ']='spam')how does this compare to out-of-bounds assignments and references for listsdoes this sound like the rule for variable names generic operations run interactive tests to answer the following questions tuplesfilesand everything else
889
( string listlist tuple) does work when one of the operands is dictionaryc does the append method work for both lists and stringshow about using the keys method on lists(hintwhat does append assume about its subject object? finallywhat type of object do you get back when you slice or concatenate two lists or two strings string indexing define string of four characterss "spamthen type the following expressions[ ][ ][ ][ ][ any clue as to what' happening this time(hintrecall that string is collection of charactersbut python characters are one-character strings does this indexing expression still work if you apply it to list such as [' '' '' '' ']why immutable types define string of four characters agains "spamwrite an assignment that changes the string to "slam"using only slicing and concatenation could you perform the same operation using just indexing and concatenationhow about index assignment nesting write data structure that represents your personal informationname (firstmiddlelast)agejobaddressemail addressand phone number you may build the data structure with any combination of built-in object types you like (liststuplesdictionariesstringsnumbersthenaccess the individual components of your data structures by indexing do some structures make more sense than others for this object files write script that creates new output file called myfile txt and writes the string "hello file world!into it then write another script that opens myfile txt and reads and prints its contents run your two scripts from the system command line does the new file show up in the directory where you ran your scriptswhat if you add different directory path to the filename passed to opennotefile write methods do not add newline characters to your stringsadd an explicit \ at the end of the string if you want to fully terminate the line in the file test your knowledgepart ii exercises
890
statements and syntax
891
introducing python statements now that you're familiar with python' core built-in object typesthis begins our exploration of its fundamental statement forms as in the previous partwe'll begin here with general introduction to statement syntaxand we'll follow up with more details about specific statements in the next few in simple termsstatements are the things you write to tell python what your programs should do ifas suggested in programs "do things with stuff,then statements are the way you specify what sort of things program does less informallypython is proceduralstatement-based languageby combining statementsyou specify procedure that python performs to satisfy program' goals the python conceptual hierarchy revisited another way to understand the role of statements is to revisit the concept hierarchy introduced in which talked about built-in objects and the expressions used to manipulate them this climbs the hierarchy to the next level of python program structure programs are composed of modules modules contain statements statements contain expressions expressions create and process objects at their baseprograms written in the python language are composed of statements and expressions expressions process objects and are embedded in statements statements code the larger logic of program' operation--they use and direct expressions to process the objects we studied in the preceding moreoverstatements are where objects spring into existence ( in expressions within assignment statements)and some statements create entirely new kinds of objects (functionsclassesand so onat the topstatements always exist in moduleswhich themselves are managed with statements
892
table - summarizes python' statement set each statement in python has its own specific purpose and its own specific syntax--the rules that define its structure-thoughas we'll seemany share common syntax patternsand some statementsroles overlap table - also gives examples of each statementwhen coded according to its syntax rules in your programsthese units of code can perform actionsrepeat tasksmake choicesbuild larger program structuresand so on this part of the book deals with entries in the table from the top through break and continue you've informally been introduced to few of the statements in table - alreadythis part of the book will fill in details that were skipped earlierintroduce the rest of python' procedural statement setand cover the overall syntax model statements lower in table - that have to do with larger program units--functionsclassesmodulesand exceptions--lead to larger programming ideasso they will each have section of their own more focused statements (like delwhich deletes various componentsare covered elsewhere in the bookor in python' standard manuals table - python statements statement role example assignment creating references ab 'good''badcalls and other expressions running functions log write("spamham"print calls printing objects print('the killer'jokeif/elif/else selecting actions if "pythonin textprint(textfor/else iteration for in mylistprint(xwhile/else general loops while yprint('hello'pass empty placeholder while truepass break loop exit while trueif exittest()break continue loop continue while trueif skiptest()continue def functions and methods def (abc= * )print( + + + [ ]return functions results def (abc= * )return + + + [ yield generator functions def gen( )for in nyield * global namespaces 'olddef function()global xyx 'newnonlocal namespaces ( xdef outer() 'old introducing python statements
893
role example def function()nonlocal xx 'newimport module access import sys from attribute access from sys import stdin class building objects class subclass(superclass)staticdata [def method(self)pass try/exceptfinally catching exceptions tryraise triggering exceptions raise endsearch(locationassert debugging checks assert ' too smallwith/as context managers ( +with open('data'as myfileprocess(myfiledel deleting references del data[kdel data[ :jdel obj attr del variable action(exceptprint('action error'technicallytable - reflects python ' statements though sufficient as quick preview and referenceit' not quite complete as is here are few fine points about its contentassignment statements come in variety of syntax flavorsdescribed in basicsequenceaugmentedand more print is technically neither reserved word nor statement in xbut built-in function callbecause it will nearly always be run as an expression statementthough (and often on line by itself)it' generally thought of as statement type we'll study print operations in yield is also an expression instead of statement as of like printit' typically used as an expression statement and so is included in this tablebut scripts occasionally assign or otherwise use its resultas we'll see in as an expressionyield is also reserved wordunlike print most of this table applies to python xtooexcept where it doesn' --if you are using python xhere are few notes for your pythontooin xnonlocal is not availableas we'll see in there are alternative ways to achieve this statement' writeable state-retention effect in xprint is statement instead of built-in function callwith specific syntax covered in in xthe exec code execution built-in function is statementwith specific syntaxsince it supports enclosing parenthesesthoughyou can generally use its call form in code python' statements
894
try statement in with/as is an optional extensionand it is not available unless you explicitly turn it on by running the statement from __future__ import with_statement (see tale of two ifs before we delve into the details of any of the concrete statements in table - want to begin our look at python statement syntax by showing you what you are not going to type in python code so you can compare and contrast it with other syntax models you might have seen in the past consider the following if statementcoded in -like languageif ( yx this might be statement in cc++javajavascriptor similar nowlook at the equivalent statement in the python languageif yx the first thing that may pop out at you is that the equivalent python statement is lesswellcluttered--that isthere are fewer syntactic components this is by designas scripting languageone of python' goals is to make programmerslives easier by requiring less typing more specificallywhen you compare the two syntax modelsyou'll notice that python adds one new thing to the mixand that three items that are present in the -like language are not present in python code what python adds the one new syntax component in python is the colon character (:all python compound statements--statements that have other statements nested inside them--follow the same general pattern of header line terminated in colonfollowed by nested block of code usually indented underneath the header linelike thisheader linenested statement block the colon is requiredand omitting it is probably the most common coding mistake among new python programmers--it' certainly one 've witnessed thousands of times introducing python statements
895
certainly forget the colon character very soon you'll get an error message if you doand most python-friendly editors make this mistake easy to spot including it eventually becomes an unconscious habit (so much so that you may start typing colons in your -like language codetoogenerating many entertaining error messages from that language' compiler!what python removes although python requires the extra colon characterthere are three things programmers in -like languages must include that you don' generally have to in python parentheses are optional the first of these is the set of parentheses around the tests at the top of the statementif ( ythe parentheses here are required by the syntax of many -like languages in pythonthoughthey are not--we simply omit the parenthesesand the statement works the same wayif technically speakingbecause every expression can be enclosed in parenthesesincluding them will not hurt in this python codeand they are not treated as an error if present but don' do thatyou'll be wearing out your keyboard needlesslyand broadcasting to the world that you're programmer of -like language still learning python ( knowbecause was oncetoothe "python wayis to simply omit the parentheses in these kinds of statements altogether end-of-line is end of statement the second and more significant syntax component you won' find in python code is the semicolon you don' need to terminate statements with semicolons in python the way you do in -like languagesx in pythonthe general rule is that the end of line automatically terminates the statement that appears on that line in other wordsyou can leave off the semicolonsand it works the same wayx there are some ways to work around this ruleas you'll see in moment (for instancewrapping code in bracketed structure allows it to span linesbutin generalyou tale of two ifs
896
required heretooif you are pining for your programming days (if such state is possibleyou can continue to use semicolons at the end of each statement--the language lets you get away with them if they are presentbecause the semicolon is also separator when statements are combined but don' do that either (really!againdoing so tells the world that you're programmer of -like language who still hasn' quite made the switch to python coding the pythonic style is to leave off the semicolons altogether judging from students in classesthis seems tough habit for some veteran programmers to break but you'll get theresemicolons are useless noise in this role in python end of indentation is end of block the third and final syntax component that python removesand the one that may seem the most unusual to soon-to-be-ex-programmers of -like languages (until they've used it for minutes and realize it' actually feature)is that you do not type anything explicit in your code to syntactically mark the beginning and end of nested block of code you don' need to include begin/endthen/endifor braces around the nested blockas you do in -like languagesif ( yx insteadin pythonwe consistently indent all the statements in given single nested block the same distance to the rightand python uses the statementsphysical indentation to determine where the block starts and stopsif yx by indentationi mean the blank whitespace all the way to the left of the two nested statements here python doesn' care how you indent (you may use either spaces or tabs)or how much you indent (you may use any number of spaces or tabsin factthe indentation of one nested block can be totally different from that of another the syntax rule is only that for given single nested blockall of its statements must be indented the same distance to the right if this is not the caseyou will get syntax errorand your code will not run until you repair its indentation to be consistent why indentation syntaxthe indentation rule may seem unusual at first glance to programmers accustomed to -like languagesbut it is deliberate feature of pythonand it' one of the main ways that python almost forces programmers to produce uniformregularand readable introducing python statements
897
readable (unlike much of the code written in -like languagesto put that more stronglyaligning your code according to its logical structure is major part of making it readableand thus reusable and maintainableby yourself and others in facteven if you never use python after reading this bookyou should get into the habit of aligning your code for readability in any block-structured language python underscores the issue by making this part of its syntaxbut it' an important thing to do in any programming languageand it has huge impact on the usefulness of your code your experience may varybut when was still doing development on full-time basisi was mostly paid to work on large old +programs that had been worked on by many programmers over the years almost invariablyeach programmer had his or her own style for indenting code for examplei' often be asked to change while loop coded in the +language that began like thiswhile ( before we even get into indentationthere are three or four ways that programmers can arrange these braces in -like languageand organizations often endure political battles and standards manuals to address the options (which seems more than little offtopic for the problem to be solved by programmingbe that as it mayhere' the scenario often encountered in +code the first person who worked on the code indented the loop four spaceswhile ( that person eventually moved on to managementonly to be replaced by someone who liked to indent further to the rightwhile ( that person later moved on to other opportunities (ending that individual' reign of coding terror )and someone else picked up the code who liked to indent lesswhile ( tale of two ifs
898
makes this "block-structured code(he sayssarcasticallynoin any block-structured languagepython or otherwiseif nested blocks are not indented consistentlythey become very difficult for the reader to interpretchangeor reusebecause the code no longer visually reflects its logical meaning readability mattersand indentation is major component of readability here is another example that may have burned you in the past if you've done much programming in -like language consider the following statement in cif (xif (ystatement else statement which if does the else here go withsurprisinglythe else is paired with the nested if statement (if ( )in ceven though it looks visually as though it is associated with the outer if (xthis is classic pitfall in the languageand it can lead to the reader completely misinterpreting the code and changing it incorrectly in ways that might not be uncovered until the mars rover crashes into giant rockthis cannot happen in python--because indentation is significantthe way the code looks is the way it will work consider an equivalent python statementif xif ystatement elsestatement in this examplethe if that the else lines up with vertically is the one it is associated with logically (the outer if xin sensepython is wysiwyg language--what you see is what you get--because the way code looks is the way it runsregardless of who coded it if this still isn' enough to underscore the benefits of python' syntaxhere' another anecdote early in my careeri worked at successful company that developed systems software in the languagewhere consistent indentation is not required even sowhen we checked our code into source control at the end of the daythis company ran an automated script that analyzed the indentation used in the code if the script noticed that we' indented our code inconsistentlywe received an automated email about it the next morning--and so did our managersthe point is that even when language doesn' require itgood programmers know that consistent use of indentation has huge impact on code readability and quality the fact that python promotes this to the level of syntax is seen by most as feature of the language also keep in mind that nearly every programmer-friendly text editor has built-in support for python' syntax model in the idle python guifor examplelines of code introducing python statements
899
key backs up one level of indentationand you can customize how far to the right idle indents statements in nested block there is no universal standard on thisfour spaces or one tab per level is commonbut it' generally up to you to decide how and how much you wish to indent (unless you work at company that' endured politics and manuals to standardize this tooindent further to the right for further nested blocksand less to close the prior block as rule of thumbyou probably shouldn' mix tabs and spaces in the same block in pythonunless you do so consistentlyuse tabs or spaces in given blockbut not both (in factpython now issues an error for inconsistent use of tabs and spacesas we'll see in then againyou probably shouldn' mix tabs or spaces in indentation in any structured language--such code can cause major readability issues if the next programmer has his or her editor set to display tabs differently than yours -like languages might let coders get away with thisbut they shouldn'tthe result can be mangled mess regardless of which language you code inyou should be indenting consistently for readability in factif you weren' taught to do this earlier in your careeryour teachers did you disservice most programmers--especially those who must read otherscode --consider it major asset that python elevates this to the level of syntax moreovergenerating tabs instead of braces is no more difficult in practice for tools that must output python code in generalif you do what you should be doing in -like language anyhowbut get rid of the bracesyour code will satisfy python' syntax rules few special cases as mentioned previouslyin python' syntax modelthe end of line terminates the statement on that line (without semicolonsnested statements are blocked and associated by their physical indentation (without bracesthose rules cover almost all python code you'll write or see in practice howeverpython also provides some special-purpose rules that allow customization of both statements and nested statement blocks they're not required and should be used sparinglybut programmers have found them useful in practice statement rule special cases although statements normally appear one per lineit is possible to squeeze more than one statement onto single line in python by separating them with semicolonsa print( bthree statements on one line this is the only place in python where semicolons are requiredas statement separators this only worksthoughif the statements thus combined are not themselves tale of two ifs