Collections » List Basics »


List Basics

Creating Modules Table Of Contents Advanced List Features

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 List

A 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 list objects to be used like arrays. In Java, an array can be created with the declaration

// 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 gradeList variable. As with all other variables in Python, no special notation is used to declare a list variable. The results of the list declaration are illustrated by the following figure

Element Access

List 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 −1, the next to last as −2 and so on as illustrated in the following diagram

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 Length

In Java, an array had a fixed size and its length was determined from the length field of the array

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 len() function

theLength = len( gradeList )
print "The list contains %d elements." % theLength

Simulating an Array

Arrays 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 (*) for use with lists. The following statement

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 ]++;

  return histogram;

Printing A List

In 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 statement as can most Python data types. Consider the statement

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 str() constructor and in fact is identical to directly printing the list.

aString = str( gradeList )

List Iteration

As with strings and files, Python provides built-in list iteration using the for loop to iterate over each item in the list.

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.


The range() function used in an earlier chapter to create a count-controlled loop is actually a function which creates and initializes a list whose elements are the corresponding index values.


Another 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 tuple class. See the Summary of Operations section in the Advanced List Features chapter for a complete list of operations available with tuples.

Creating Modules Table Of Contents Advanced List Features

© 2006 - 2008: Rance Necaise - Page last modified on July 31, 2008, at 10:12 AM