|
List BasicsCreating Modules Table Of Contents Advanced List Features Page Contents (hide) Python does not provide the simple array type like that found in Java and other languages. Instead, it provides the built-in list type which is a dynamic array similar to a Vector in Java. The Python list defines a positional ordering from left to right like an array, but its size can change during execution as items are added and deleted. In this chapter, we explore the use of the Python list in a fashion similar to arrays in Java. The dynamic array or vector type features are presented in the following chapter. Creating a ListA Python list is a built-in type which stores a collection of object references like Vector objects in Java. Instead of providing two indexed collection types — arrays and vectors — as is done in Java, Python makes it easy for // Java array declaration. int [] gradeList = { 85, 90, 87, 65, 91 }; An equivalent list can be created in Python by specifying the element values within square brackets gradeList = [ 85, 90, 87, 65, 91 ] creates a five element list of integers containing the given values and the list reference is stored in the Element AccessList elements are referenced using the square bracket subscript notation, the same as in Java. The elements are numbered in sequential order, with the first element having index zero. A feature of Python not found in Java is the ability to reference elements in reverse order using negative indicies; the same as can be done with Python strings. The last element of the list is referenced as To demonstrate element access in Python, consider the following statements print "Forward:", gradeList[ 0 ], gradeList[ 3 ] print "Reverse:", gradeList[ -1 ], gradeList[ -3 ] which produces the following output Forward: 85 65 Reverse: 91 87 As in Java, if you attempt to reference an element that is out or range (beyond the end or the front when using reverse indexing), an exception is raised. List LengthIn Java, an array had a fixed size and its length was determined from the double [] scores = new double[ 35 ]; System.out.print( "Array size = " + scores.length ); In Python, the size of a list can be easily changed by adding or deleting elements. But we are still able to obtain the current size of the list using the built-in theLength = len( gradeList ) print "The list contains %d elements." % theLength Simulating an ArrayArrays in Java are created with a fixed number of elements immediately available for access. // Java grade histogram array. int [] gradeHist = new int[ 10 ]; Python lists are variable length, however, and can change size during the execution of the program. There is no equivalent command to create a fixed size list. But we can simulate a Java array be creating a list with a preset number of elements. Python defines the repeat operator ( gradeHist = [ 0 ] * 10 creates a 10 element list with each element being initialized with a value of zero. Since all 10 elements exist, the list can now be used just like an array in Java. Consider the following function definition which takes an integer array containing exam grades and produces a histogram containing the number of occurrences of each 10-point grade range. def makeHistogram( gradeList ) : # Create a 10 element histogram. histogram = [ 0 ] * 10 # Count the number of each grade. i = 0 while i < len( gradeList ) : grade = gradeList[ i ] / 10 histogram[ grade ] += 1 i += 1 # Return the histogram. return histogram A Java equivalent would be public static int[] makeHistogram( int[] gradeList ) { // Create and initialize the histogram. int[] histogram = new int[ 10 ]; // Count the number of each grade. int i = 0; while( i < gradeList.length ) { int grade = gradeList[ i ] / 10; histogram[ grade ]++; i++; } return histogram; } Printing A ListIn Java, to print the entire contents of an array requires a count-controlled loop. // Java array printing. System.out.print( "[" ); for( int i = 0; i < gradeList.length; i++ ) { System.out.print( gradeList[ i ] ); if( i < gradeList.length-1 ) System.out.print( ", " ); } System.out.println( "]" ); In Python, a list can be printed using the print gradeList which produces the following output [95, 90, 87, 65, 91] The contents of a list can also be converted to a string using the aString = str( gradeList ) List IterationAs with strings and files, Python provides built-in list iteration using the total = 0 for value in valueList : total = total + value avg = float( total ) / len( valueList ) print "The average value = %6.2f" % avg During the iteration of the loop, each element of the list is assigned, in turn, to the loop variable beginning with the element at index zero. Note, that the number of iterations is the number of elements in the list. If you are using the list as if it were an array in Java, it may iterate too many times.
TuplesAnother built-in type for creating an indexed collection of objects is the tuple. Tuples are exactly like lists, except they are immutable. A tuple is created using a pair of parentheses instead of square brackets. t = ( 0, 2, 4 ) # 3 element tuple a = ( 2, ) # 1 element tuple b = ( 'abc', 1, 4.5, 5 ) # 4 element mixed tuple c = ( 0, ( 'a', 'b' ) ) # nested tuple You have already seen the use of tuples. When multiple values are passed as data fields in a formatted string, those values are listed within parentheses. That is actually a tuple. print "(%d, %d)" % (x, y) Many of the list operations can be used with tuples, but there are no methods defined for the | |||
© 2006 - 2008: Rance Necaise - Page last
modified on July 31, 2008, at 10:12 AM
|