Collections » Advanced List Features »

 

Advanced List Features

List Basics Table Of Contents Text Files


The Python list class is a dynamic array type similar to the Vector class in Java. In the previous chapter, we used the Python list in a manner similar to arrays in Java. Here, we explore the advanced featuers of the list class and compare it to the corresponding operations of the Java Vector class.

A vector structure is similar to an array in that the items can be accessed via an integer index. But it differs in that the size can change as items are added or removed. For simplicity, Python provides one structure for both array and vector needs.

Adding New Items

In the examples from the earlier chapter, we created a list of a given size, filled it as needed, and processed its elements. Now, we are going to extend that concept and treat the list as intended in Python. We can start with an empty list, indicted by empty brackets (:javacmd vector = new Vector(); :)

valueList = []
 

and add new items as needed. The size of the list expands as new items are added. The number of elements or size of the list is always the same as the number of items it contains.

Appending Items

New items can be appended to the end of the list using the append() method. In Java, this was done using the add method of the Vector class. The following code segment creates a list of 1000 random values

(:javacmd vector.add( item ); :)

import random

# Create the empty list.
valueList = []

# Build the list of random values.
for i in range( 1000 ) :
   valueList.append( random.random() )
 

Appending Multiple Items

The extend() method can be used to append multiple items to the end of a list. Executing the following statements

listA = [ 0, 1, 2, 3 ]
listB = listA.extend( [ 4, 5, 6 ] )
print listB
 

produces as output

[0, 1, 2, 3, 4, 5, 6 ]

The extend() method takes a single argument which must be list object. The entire contents of the argument is appended to the end of the list for which the method was invoked.

Inserting Items

Python defines the insert() list method for inserting items anywhere within a list. Consider the code segment

(:javacmd vector.add( 1, 8 ); :)

values = [ 0, 1, 2, 3, 4 ]
values.insert( 1, 8 )
print values
 

which produces the following output

[0, 8, 1, 2, 3, 4]

As you will notice, the insert() method inserted value 8 before the current item at position 1. A new element was added and the remaining items were shifted down. The prototype of the insert() method is defined as

list.insert( atIndex, value )

where

atIndex
is the element index at which the value is to be inserted. If atIndex is beyond the end of the list, the value is appended to the end. Negative indicies can be used to reference a particular element from the end of the list.
value
The value to be inserted. Remember, that an alias is created for the given value and inserted into the list.

The following example uses the insert() method to create an ordered list of integer values extracted from a text file.

# orderednums.py
#
# Extracts a list of integers from a text file, one per line
# and creates an ordered list using the insert() method.

# Start with an empty list.
theList = []

theFile = file( "values.txt", "r" )
for line in theFile:
   num = int( line )
   
     # Find the proper position of the item.
   i = 0
   while i < len( theList ) and num > theList[ i ]:
      i = i + 1
     
     # Insert the item.
   theList.insert( i, num )
   
theFile.close()
print theList
 

An equivalent implementation in Java is illustrated below

// OrderedList.java
//
// Extracts a list of integers from a text file, one per line
// and creates an ordered list using the add() method.

import java.util.*;

public class OrderedList {
  public static void main( String[] args ) {
    Scanner theFile = new Scanner( new File( "values.txt" ) );
    Vector theList = new Vector();
   
    while( theFile.hasNext() ) {
      int num = theFile.nextInt();
     
      int i = 0;
      while( i < theList.size() && num > theList.elementAt( i ) )
        i = i + 1;
     
      theList.add( i, num );
    }
   
    theFile.close();
    for( int i = 0; i < theList.size(); i++ )
      System.out.print( theList.elementAt( i ) + " " );
    System.out.println();
  }
}
 

Removing Items

Python provides several means for deleting items from a list. The first approach uses the remove() method which allows you to delete an item by value.

(:prototype list.remove( item ):)

theList = [ 10, 11, 12, 13 ]
theList.remove( 11 )
print theList       # prints [10, 12, 13]
 

To remove an item by index, you can use the pop() method which retrieves and then removes the item at the given index. In the following code segment, we use the pop() method to retrieve and remove the item at index position one. This segment

(:prototype list.pop( index = 0 ):)

x = theList.pop( 1 )
print "list =", theList
print "x =", x
 

will produce as output

list = [10, 13]
x = 12

When an item is removed from the list, the items in sequential order following the removed item are shifted down and the size of the list shrinks by one. You can omit the index position for pop() and the item in the last element will be retrieve and removed.

theList.pop()
print theList     # prints [10]
 

As in Java, when all references to an object are removed, the object is marked as garbage and will be delete as part of the garbage collection. When an item is removed or deleted from a list, if there are no other aliases for that item, it becomes garbage and eventually deleted by the systme.

Searching

The Python list class provides several methods and operators that can be used to search a list. In Java, some of these would have to be implemented using a loop.

Item Search

You can search for an item within the list using the index() method which returns the element index of the first occurrence in thelist of the given value. If the list does not contain the given value, an exception is raised.

(:prototype list.index( item ):)

theList = [ 10, 11, 12, 13 ]
pos = theList.index( 13 )
print pos         
# prints 3
 

Membership

As with strings, the in operator (and the not in version) can be used to determine if the list contains a given item.

(:prototype item in list:)

if 100 in gradeList :
   print "Student received at least one perfect score."
 

In Java, this operation would require an explicit loop used to search for the given item

// Java item search.
int i = 0;
while( i < gradeList.length ) {
  if( gradeList[ i ] == 100 )
    System.out.println( "Someone received at least one "
                      + " perfect score." );
  i++;
}
 

While the in operator can be used to determine if an item is in the list, sometimes you may also need to know the index of that item. Python defines the index() operator for this purpose. Given the following code segment

print gradeList.index( 90 )
 

Python would print 1 when this statement is executed assuming the gradeList is defined from the example above. If the value is not in the list, an exception is raised. Thus, the index() method should be used in conjunction with the in operator.

if 90 in gradeList :
   print gradeList.index( 90 )
else :
   print "Grade not in list."
 

A third membership list operation provided by Python counts the number of occurrences of a particular item in the given list. For example, if we wanted to know how many perfect scores are in gradeList, we can use the count() method

(:prototype list.count( item ):)

print "The student has ", gradeList.count( 100 ),
      " perfect scores."
 

Min and Max

Two other operations commonly performed on lists, especially those containing numeric values, is a search for the minimum or maximum value. In Python, these are easily found using the min() and max() functions.

print "The minimum value = ", min( valueList )
print "The maximim value = ", max( valueList )
 

Concatenation and Duplication

Earlier we used the concatenation operator to concatenate two strings resulting in a third string. Python also defines this operation for lists. Assume we have two lists

listA = [ 1, 2, 3 ]
listB = [ 8, 9 ]
 

which can be concatenated to produce a third list. If we execute the statements

bigList = listA + listB
print bigList
 

the result will be

[1, 2, 3, 8, 9]

List concatenation can be used to create a duplicate copy of a list. Remember that the assignment statement creates reference aliases when one variable is assigned to another. In the following code, listY is an alias for listX. Thus, when we make a change to listY, that change also affects listX.

listX = [ 1, 2, 3 ]
listY = listX
listY[0] = 0
print "X:", listX
print "y:", listY
 

The output from executing the previous statements is

X: [0, 2, 3]
Y: [0, 2, 3]

If you want to create a duplicate copy of a list, concatenate your list with the empty list. This new code segment

listX = [ 1, 2, 3 ]
listY = listX + []
listY[0] = 0
print "X:", listX
print "y:", listY
 

will now produce the following since listY now references a new list which happens to be a duplicate copy of listX.

X: [1, 2, 3]
Y: [0, 2, 3]

Reverse

The reverse() method is used to reverse the order of the items in the list.

theList = [ 10, 11, 12, 13 ]
theList.reverse()
print theList       
# prints [13, 12, 11, 10]
 

Replication

We used the repeat operator to create a list with a given size in order to use it like an array in Java. But this operator can be used to repetitively copy any list. The contents of the given list is replicated the number of times indicated by the integer value on the right hand side. If the list contains multiple values, all of the values are replicated in order. In the following example, we create a 100 element integer list with the sequence of values [0..4] repeating at every 5th element.

intList = [ 0, 1, 2, 3, 4 ] * 25
 

List Slices

Summary of Operations

The following table summarizes the methods and operators available for use with Python lists.

Operation Description
List Operators
a = [] Create an empty list. This is equivalent to creating a Vector object in Java.
b = [0, 1, 2] Create a list using a literal list representation.
b[i] Access the ith element of list b.
b * 4 Replicate the elements of list b four times to create a new list.
a + b Concatenate the elements of lists a and b to create a new list.
del b[i] Delete the ith element from list b.
for x in list Iterate over each element in the list.
x in list Determine if x is an element in the list.
len( b ) Returns the length or the number of elements of list b.
Class Methods
append( obj ) Appends the object obj to the end of the list.
extend( listobj ) Appends all items in list listobj to the end of the list.
index( obj ) Searches the list and returns the index of the first element containing the obj item. The search is based on the value of te object and not the reference. If the item is not in the list, an exception is raised.
reverse() Reverses the ordering of the items within the list.
sort() Sort the elements of the list in ascending order.



List Basics Table Of Contents Text Files

© 2006 - 2008: Rance Necaise - Page last modified on September 19, 2006, at 03:04 PM