Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Python Csc 667/867 Course note credit to PrenticeHall Printing a Line of Text • Python Online Tutorial http://www.python.org/doc/current/tut/ • Python Reference Manual http://docs.python.org/ref/contents.html • Executing – Saving as a file • Type code into a .py file and save it • To run it type python fileName.py – Executing code • Type python in the command line • Runs the python interpreter 2 Adding Integers • Functions – The raw_input function • Used to retrieve data from the user – The int function • Used to convert strings to integers 3 1 2 3 4 5 6 7 8 9 10 11 12 13 # Fig. 2.7: fig02_07.py # Simple addition program. # prompt user for input integer1 = raw_input( "Enter first integer:\n" ) # read string integer1 = int( integer1 ) # convert string to integer integer2 = raw_input( "Enter second integer:\n" ) # read string integer2 = int( integer2 ) # convert string to integer sum = integer1 + integer2 print "Sum is", sum # compute and assign sum # print sum Enter first integer: 45 Enter second integer: 72 Sum is 117 4 Another Program: Adding Integers Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> value1 = raw_input( "Enter an integer: " ) Enter an integer: 2 >>> value2 = raw_input( "Enter an integer: " ) Enter an integer: 4 >>> print value1 + value2 24 Fig. 2.8 Adding values from raw_input (incorrectly) without converting to integers (the result should be 6). 5 Arithmetic • Symbols – – – – – * = multiply / = divide % = modulus ** = exponential // = floor division • Only available in Python 2.2 • Must use from __future__ import division • Order – Operators are done in order of parenthesis, exponents, multiple and divide (left to right), and lastly add and subtract (left to right) 6 Arithmetic Op era tor(s) Op era tion(s) Ord er of Eva lua tion (Prec ed enc e) () Parentheses ** Exponentiation Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right. Evaluated second. If there are several, they are evaluated right to left. * / // % Multiplication Division Modulus Evaluated third. If there are several, they are + - Addition Subtraction Evaluated last. If there are several, they are evaluated left to right. evaluated left to right. [Note: The // operator is new in version 2.2] Fig. 2.16 Prec ed enc e of a rithmetic op era tors. 7 Augmented Assignment Symbols Assig nm e nt sym b ol Sa m p le exp ression Exp la na tio n Assig ns c += 7 d -= 4 e *= 5 c = c + 7 d = d - 4 e = e * 5 10 to c f = f ** 3 g = g / 3 h = h % 9 8 to f Assume: c = 3, d = 5, e = 4, f = 2, g = 6, h = 12 += -= *= **= f **= 3 /= g /= 3 %= h %= 9 Fig. 3.16 Aug m ented a rithm etic 1 to d 20 to e 2 to g 3 to h a ssig nm ent sym b ols. 8 Logical Operators • Operators – and • Evaluates to true if both expressions are true – or • Evaluates to true if at least one expression is true – not • Returns true if the expression is false • Not required in any program 9 String Formatting • Strings – Unlike other languages strings are a built in data type • Allows for easy string manipulation – Double quote strings • Single quotes need not be escaped – Single quote strings • Double quotes need not be escaped – Triple quoted strings • Do not need any escape sequence • Used for large blocks of text 10 1 2 3 4 5 6 7 8 9 10 # Fig. 2.18: fig02_18.py # Creating strings and using quote characters in strings. print "This is a string with \"double quotes.\"" print 'This is another string with "double quotes."' print 'This is a string with \'single quotes.\'' print "This is another string with 'single quotes.'" print """This string has "double quotes" and 'single quotes'. You can even do multiple lines.""" print '''This string also has "double" and 'single' quotes.''' This is a string with "double quotes." This is another string with "double quotes." This is a string with 'single quotes.' This is another string with 'single quotes.' This string has "double quotes" and 'single quotes'. You can even do multiple lines. This string also has "double" and 'single' quotes. 11 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # String formatting. integerValue = 4237 print "Integer ", integerValue print "Decimal integer %d" % integerValue print "Hexadecimal integer %x\n" % integerValue floatValue = 123456.789 print "Float", floatValue print "Default float %f" % floatValue print "Default exponential %e\n" % floatValue print "Right justify integer (%8d)" % integerValue print "Left justify integer (%-8d)\n" % integerValue stringValue = "String formatting" print "Force eight digits in integer %.8d" % integerValue print "Five digits after decimal in float %.5f" % floatValue print "Fifteen and five characters allowed in string:" print "(%.15s) (%.5s)" % ( stringValue, stringValue ) 12 Integer 4237 Decimal integer 4237 Hexadecimal integer 108d Float 123456.789 Default float 123456.789000 Default exponential 1.234568e+005 Right justify integer ( Left justify \integer 4237) (4237 ) Force eight digits in integer 00004237 Five digits after decimal in float 123456.78900 Fifteen and five characters allowed in string: (String formatti) (Strin) 13 Indentation • Indenting – Used to delimit code – Python uses no end of statement character – Therefore a new line of code is determined by return space – Indenting is the same way • Python does not use {} to enclose a multi-line statement • The indentation must be exactly the same same – There is no exact rule for the number of spaces but they are generally in groups of three 14 Lines • Logical Lines (http://docs.python.org/ref/logical.html) • Physical Lines • Explicit Line Joining if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 • Implicit Line Joining month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year 15 Control Structure • Sequential order – Statements are executed in the order they are written • Transfer of control – A program executes a statement other than the following one – The goto statement • Allows a program to go to a wide range of areas in the code • Structured programming was broken with the use of goto • Any code can be written without a goto statement – Selection structure • The if statement • The if/else statement • The if/elif/else statement – Repetition structure • The while repetition structure • The for repetition structure 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 # Control Statement examples # Class average program with counter-controlled repetition. # initialization phase total = 0 # sum of grades gradeCounter = 1 # number of grades entered # processing phase while gradeCounter <= 10: # loop 10 times grade = raw_input( "Enter grade: " ) # get one grade grade = int( grade ) # convert string to an integer total = total + grade gradeCounter = gradeCounter + 1 # termination phase average = total / 10 # integer division print "Class average is", average 17 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # More control statement example # Class average program with sentinel-controlled repetition. # initialization phase total = 0 # sum of grades gradeCounter = 0 # number of grades entered # processing phase grade = raw_input( "Enter grade, -1 to end: " ) # get one grade grade = int( grade ) # convert string to an integer while grade != -1: total = total + grade gradeCounter = gradeCounter + 1 grade = raw_input( "Enter grade, -1 to end: " ) grade = int( grade ) # termination phase if gradeCounter != 0: average = float( total ) / gradeCounter print "Class average is", average else: print "No grades were entered" 18 break and continue Statements • The break statement – Used to make a loop stop looping – The loop is exited and no more loop code is executed • The continue statement – Used to continue the looping process – All following actions in the loop are not executed • But the loop will continue to run 19 1 2 3 4 5 6 7 8 9 10 11 # Fig. 3.24: fig03_24.py # Using the break statement in a for structure. for x in range( 1, 11 ): if x == 5: break print x, print "\nBroke out of loop at x =", x 1 2 3 4 Broke out of loop at x = 5 20 Logical Operators Python 2.2b2 (#26, Nov 16 Type "help", "copyright", >>> if 0: ... print "0 is true" ... else: ... print "0 is false" ... 0 is false >>> if 1: ... print "non-zero is ... non-zero is true >>> if -1: ... print "non-zero is ... non-zero is true >>> print 2 < 3 1 >>> print 0 and 1 0 >>> print 1 and 3 3 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 "credits" or "license" for more information. true" true" Fig. 3.28 Truth values. 21 Variable Scope def demo (f_in): global somevar # shared with main code demo.tom = 16 # An attribute accessible from main code somevar += 1 f_in = 2 demo.another = 12 # A local variable, independent of main code another = 13 res = f_in+14 # Value passed in (f_in) return res somevar = 27 # accessed in function via global another = 17 # not accessed in function pval = 16 # accessed in function via parameter print demo(pval) print pval print demo.tom # function attribute print somevar print another print demo.another 22 Using Lists Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> aList = [ 1 ] >>> print aList[ 13 ] Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: list index out of range Fig. 5.4 Out-of-range error. 23 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # Fig. 5.5: fig05_05.py # Creating a histogram from a list of values. values = [] # a list of values # input 10 values from user print "Enter 10 integers:" for i in range( 10 ): newValue = int( raw_input( "Enter integer %d: " % ( i + 1 ) ) ) values += [ newValue ] # create histogram print "\nCreating a histogram from values:" print "%s %10s %10s" % ( "Element", "Value", "Histogram" ) for i in range( len( values ) ): print "%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] ) 24 Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter 10 integers: integer 1: 19 integer 2: 3 integer 3: 15 integer 4: 7 integer 5: 11 integer 6: 9 integer 7: 13 integer 8: 5 integer 9: 17 integer 10: 1 Creating a histogram from values: Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 * Fig05_05.py Program Output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 # Fig. 5.6: fig05_06.py # Creating and accessing tuples. # retrieve hour, minute and second from user hour = int( raw_input( "Enter hour: " ) ) minute = int( raw_input( "Enter minute: " ) ) second = int( raw_input( "Enter second: " ) ) currentTime = hour, minute, second # create tuple print "The value of currentTime is:", currentTime # access tuple print "The number of seconds since midnight is", \ ( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 + currentTime[ 2 ] ) Enter hour: 9 Enter minute: 16 Enter second: 1 The value of currentTime is: (9, 16, 1) The number of seconds since midnight is 33361 26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # Fig. 5.09: fig05_09.py # Creating, accessing and modifying a dictionary. # create and print an empty dictionary emptyDictionary = {} print "The value of emptyDictionary is:", emptyDictionary # create and print a dictionary with initial values grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } print "\nAll grades:", grades # access and modify an existing dictionary print "\nSteve's current grade:", grades[ "Steve" ] grades[ "Steve" ] = 90 print "Steve's new grade:", grades[ "Steve" ] # add to an existing dictionary grades[ "Michael" ] = 93 print "\nDictionary grades after modification:" print grades # delete entry from dictionary del grades[ "John" ] print "\nDictionary grades after deletion:" print grades 27 The value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76 Steve's new grade: 90 Dictionary grades after modification: {'Edwin': 89, 'Michael': 93, 'John': 87, 'Steve': 90, 'Laura': 92} Dictionary grades after deletion: {'Edwin': 89, 'Michael': 93, 'Steve': 90, 'Laura': 92} 28 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # Fig. 5.17: fig05_17.py # Sorting a list. aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ] print "Data items in original order" for item in aList: print item, aList.sort() print "\n\nData items after sorting" for item in aList: print item, print Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items after sorting 2 4 6 8 10 12 37 45 68 89 29 List and Dictionary Methods Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dictionary = { "listKey" : [ 1, 2, 3 ] } >>> shallowCopy = dictionary.copy() # make a shallow copy >>> dictionary[ "listKey" ].append( 4 ) >>> print dictionary {'listKey': [1, 2, 3, 4]} >>> print shallowCopy {'listKey': [1, 2, 3, 4]} >>> from copy import deepcopy >>> deepCopy = deepcopy( dictionary ) >>> dictionary[ "listKey" ].append( 5 ) >>> print dictionary {'listKey': [1, 2, 3, 4, 5]} >>> print shallowCopy {'listKey': [1, 2, 3, 4, 5]} >>> print deepCopy {'listKey': [1, 2, 3, 4]} # make a deep copy Fig. 5.15 Difference between a shallow copy and a deep copy. 30 Modules • Check http://www.python.org/doc/current/tut/node8.html • Import, from • The Module Search Path – in the current directory – And then in the list of directories specified by the environment variable PYTHONPATH >>> import fibo >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo' If you intend to use a function often you can assign it to a local name: >>> fib = fibo.fib >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 >>> from fibo import fib, fib2 >>> fib(500) # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result 31 Fibo.py CGI module http://docs.python.org/lib/module-cgi.html form = cgi.FieldStorage() if not (form.has_key("name") and form.has_key("addr")): print "<H1>Error</H1>" print "Please fill in the name and addr fields." return print "<p>name:", form["name"].value print "<p>addr:", form["addr"].value … value = form.getlist("username") usernames = ",".join(value) … fileitem = form["userfile"] 32 1 2 3 4 6 7 8 9 12 14 15 16 19 21 23 24 25 26 27 28 30 31 32 33 34 35 #!c:\Python\python.exe # Fig. 6.5: fig06_05.py # Program displaying CGI environment variables. import os import cgi def printHeader( title ): print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head><body>""" % title rowNumber = 0 backgroundColor = "white" printHeader( "Environment Variables" ) Function cgi.escape print """<table style = "border: 0">""" takes a string and returns a properly # print table of cgi variables and values for item in os.environ.keys(): formatted XHMTL string rowNumber += 1 if rowNumber % 2 == 0: # even row numbers are white backgroundColor = "white" else: # odd row numbers are grey backgroundColor = "lightgrey" print """<tr style = "background-color: %s"> <td>%s</td><td>%s</td> </tr>""" % ( backgroundColor,cgi.escape( item ), cgi.escape(os.environ[ item ])) 39 print """</table></body></html>""" 33 fig06_05.py 34 1 2 6 7 8 9 10 11 13 15 17 19 20 21 22 23 24 25 26 27 28 30 31 32 33 34 35 37 38 40 #!c:\Python\python.exe import os import cgi def printHeader( title ): print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title printHeader( "QUERY_STRING example" ) print "<h1>Name/Value Pairs</h1>" query = os.environ[ "QUERY_STRING" ] if len( query ) == 0: print """<p><br /> Please add some name-value pairs to the URL above. Or try <a href = "fig06_06.py?name=Veronica&age=23">this</a>. </p>""" else: print """<p style = "font-style: italic"> The query string is '%s'.</p>""" % cgi.escape( query ) pairs = cgi.parse_qs( query ) for key, value in pairs.items(): print "<p>You set '%s' to value %s</p>"" % \ ( key, value ) print "</body></html>" 35 36 1 2 6 7 8 9 10 12 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #!c:\Python\python.exe import cgi def printHeader( title ): print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head> <body>""" % title printHeader( "Using 'post' with forms" ) print """<p>Enter one of your favorite words here:<br /></p> <form method = "post" action = "fig06_09.py"> <p> <input type = "text" name = "word" /> <input type = "submit" value = "Submit word" /> </p> </form>""" pairs = cgi.parse() if pairs.has_key( "word" ): print """<p>Your word is: <span style = "font-weight: bold">%s</span></p>""" \ % cgi.escape( pairs[ "word" ][ 0 ] ) print "</body></html>" 37 38 Cookie • http://wp.netscape.com/newsref/std/cookie_spe c.html – Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure – Cookie: NAME1=OPAQUE_STRING1; NAME2=OPAQUE_STRING2 ... • Response goes with “Set-Cookie” and then Request comes with “Cookie” • Cookie example at unicorn.sfsu.edu/cgi667/cookiecounter.py 39 Check http://docs.python.org/lib/module-Cookie.html for detail information for cgi module #!/usr/bin/env python from Cookie import SimpleCookie import cgi import os def getCookie(initialvalues = {}): """Return a SimpleCookie. If some of the cookie values haven't been set, we'll plunk them into the cookie with the initialValues dict.""" if os.environ.has_key('HTTP_COOKIE'): C = SimpleCookie(os.environ['HTTP_COOKIE']) else: C = SimpleCookie() for key in initialvalues.keys(): if not C.has_key(key): C[key] = initialvalues[key] return C if __name__ == '__main__': cookie = getCookie({'counter': 0}) cookie['counter'] = int(cookie['counter'].value) + 1 print cookie print "content-type: text/plain\n\n" print "Here's our count:", cookie['counter'].value 40 Sequences • Sequence – – – – Series of items that are often related Strings are sequences in Python A sequence is returned by the range function Elements • The individual items in each sequence – Referred to by subscripts • The first is always zero • Obtain one by using sequenceName[ subscript ] • Can also be referred to negatively – -1 would be the last element of the sequence 41 Sequences Name sequence (c) Position number of the element within sequence c Fig. 5.1 c[ 0 ] -45 c[ -12 ] c[ 1 ] 6 c[ -11 ] c[ 2 ] 0 c[ -10 ] c[ 3 ] 72 c[ -9 ] c[ 4 ] 1543 c[ -8] c[ 5 ] -89 c[- 7 ] c[ 6 ] 0 c[ -6 ] c[ 7 ] 62 c[ -5 ] c[ 8] -3 c[ -4 ] c[ 9 ] 1 c[- 3 ] c[ 10 ] 6453 c[ -2 ] c[ 11 ] -78 c[ -1 ] Sequence with elements and indices. 42 Creating Sequences • Creations – Strings • Use quotes • string1 = "" – Lists • Use brackets • Separate multiple items with a comma • list1 = [] – Tuples • Use parenthesis • Separate multiple items with a comma • tuple = () 43 Using Lists and Tuples • Differences – Tuples and lists can both contain the same data – For practical purposes though each is used to hold different types of items 44 Using Lists • Lists – Not restricted to values of the same type • Programmers use lists to hold data that is of the same type – The length is not usually predetermined and can vary throughout the program – Accessing elements out of range • Python exits and an out of range error is displayed 45 Using Tuples • Tuples – Used to contain data that is related but not necessarily of the same type • Each data item represents a unique piece of the overall portion – In this case tuples are usually not iterated though – The needed data is accessed before hand • A person’s name, age and birth date • Again this is not required but is a general rule 46 Sequence Unpacking • Unpacking – A useful shortcut for to assign values to multiple variables in one statement Sequence Slicing • Slicing – Allows a programmer to access a portion of a string or element at once – theSequence [ start:end ] – Returns the portion of the sequence from the starting position up to the ending position 47 Unpacking string... String values: a b c Unpacking list... List values: 1 2 3 Unpacking tuple... Tuple values: a A 1 Before swapping: x = 3, y = 4 After swapping: x = 4, y = 3 1 2 3 5 6 7 9 10 11 12 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 # Fig. 5.7: fig05_07.py # Unpacking sequences. # create sequences aString = "abc" aList = [ 1, 2, 3 ] aTuple = "a", "A", 1 # unpack sequences to variables print "Unpacking string..." first, second, third = aString print "String values:", first, second, third print "\nUnpacking list..." first, second, third = aList print "List values:", first, second, third print "\nUnpacking tuple..." first, second, third = aTuple print "Tuple values:", first, second, third # swapping two values x=3 y=4 print "\nBefore swapping: x = %d, y = %d" % ( x, y ) x, y = y, x # swap variables print "After swapping: x = %d, y = %d" % ( x, y ) 48 1 2 4 5 6 7 10 11 12 13 14 16 17 18 20 21 24 27 # Fig. 5.8: fig05_08.py # Slicing sequences. # create sequences sliceString = "abcdefghij" sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) sliceList = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ] # print strings print "sliceString: ", sliceString print "sliceTuple: ", sliceTuple print "sliceList: ", sliceList print # get slices start = int( raw_input( "Enter start: " ) ) end = int( raw_input( "Enter end: " ) ) # print slices print "\nsliceString[", start, ":", end, "] = ", sliceString[ start:end ] print "sliceTuple[", start, ":", end, "] = ", sliceTuple[ start:end ] print "sliceList[", start, ":", end, "] = ", sliceList[ start:end ] sliceString: abcdefghij sliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] Enter start: -4 Enter end: -1 sliceString[ -4 : -1 ] = ghi sliceTuple[ -4 : -1 ] = (7, 8, 9) sliceList[ -4 : -1 ] = ['VII', 'VIII', 'IX'] 49 Dictionaries • Dictionaries – Mapping constructs consisting of key-value pairs • Referred to as hashes in other languages – – – – Unordered collection of references Each value is referenced though key in the pair Curley braces ({}) are used to create a dictionary When entering values • Use { key1:value1, … } – Keys must be immutable values such as strings, numbers and tuples – Values can be of any Python data type 50 List and Dictionary Methods Method Purp ose append( item ) Inserts item at the end of the list. count( element ) Returns the number of occurrences of element in the list. extend( newList ) Inserts the elements of newList at the end of the list. index( element ) Returns the index of the first occurrence of element in the list. If element is not in the list, a ValueError exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] insert( index, item ) Inserts item at position index. pop( [index] ) Parameter index is optional. If this method is called without arguments, it removes and returns the last element in the list. If parameter index is specified, this method removes and returns the element at position index. remove( element ) Removes the first occurrence of element from the list. If element is not in the list, a ValueError exception occurs. reverse() Reverses the contents of the list in place (rather than creating a reversed copy). sort( [comparefunction] ) Sorts the content of the list in place. The optional parameter compare-function is a function that specifies the compare criteria. The compare-function takes any two elements of the list (x and y) and returns -1 if x should appear before y, 0 if the orders of x and y do not matter and 1 if x should appear after y. [Note: We discuss sorting in Section 5.9.] Fig. 5.12 List method s. 51 List and Dictionary Methods Me thod De sc rip tio n clear() Deletes all items from the dictionary. copy() Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary). get( key [, returnValue] ) Returns the value associated with key. If key is not in the dictionary and if returnValue is specified, returns the specified value. If returnValue is not specified, returns None. has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is not in the dictionary. items() Returns a list of tuples that are key-value pairs. keys() Returns a list of keys in the dictionary. popitem() Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a Key- Error exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] This method is useful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary. 52 List and Dictionary Methods setdefault( key [, dummyValue] ) Behaves similarly to method get. If key is not in the dictionary and dummyValue is specified, inserts the key and the specified value into dictionary. If dummyValue is not specified, value is None. update( newDictionary ) Adds all key-value pairs from newDictionary to the current dictionary and overrides the values for keys that already exist. values() Returns a list of values in the dictionary. iterkeys() Returns an iterator of dictionary keys. [ Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] iteritems() Returns an iterator of key-value pairs. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] itervalues() Returns an iterator of dictionary values. [ Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.] Fig. 5.14 Dic tio na ry m e tho d s. 53