GIS Logo GSP 118 (318): GIS Programming

For Loops

In Review

1. "For" loops

"For" loops will "iterate" through each of the elements in a list. The example below sets "TheList" to contain some different types of plants and then prints out each of the elements of the list. The "for" statement will set the variable "Type" to the first element of the list,execute the code within the "for" loop and then repeat for each of the elements in the list. Notice that there is a colon at the end of the "for" statement and then all the code in the "loop" is indented by one space or tab.

TheList=['tree', 'shrub', 'grass', 'fern']
for Type in TheList:
	print(Type) 

Combining lists created with the "range()" function allows you to create a "for" loop that iterates through a series of numbers. This is very common in programming. An example is:

for x in range(0,10):
    print(x)

You can also add the "step"

for x in range(0,10,2):
    print(x)

2. Iterating through existing lists with indexes

Sometimes you'll want to iterate through a list and know which index you are on. This is commonly used when you have a list of values and want to know which "row" you are on. The following will print the values and the index:

TheList= [1.5,2.3,4.5,8.3]
for Index in range(len(TheList)):
 print Index, TheList[Index]

3. Nested For Loops

When we are processing data in tables we may want to go to each row in the table and then look at each cell in each row. This requires a "for" loop to go through the rows and a "nested" "for" loop to go through each cell. Try code like the example below to see how you can "next" for loops. Use the debugger to step through this code and watch how the row will first be set to 0, then the code will go through each value of the column before moving the row to the next value. Then it will go through the column values again.

for row in range(0,10): # go through the code below for each value from 0 to 9
   for column in range(0,4): # go through the code below for each value from 0 to 4
   	print(format(row)+","+format(column))

This approach also allows you to process raster files and other multi-dimensional datasets.

Additional Resources

Python Documentation: More Control Flow Tools