How Does Python’s Range Function Work When Three Parameters Are Passed?

Problem scenario
You see this line of Python code:  for x in range ( len(coolList), 0, -1 ): print x
You are curious how that works and what that syntax means.

Answer
The first of the three parameters is the integer that corresponds to the starting number of the iteration.  The second variable is the range position that will terminate the iteration of the range function.  The third variable is the incremental value (e.g., -1, 1, 2, etc.).

A range will operate with a start, finish, and an incremental value (all pertaining to zero-based lists.  The len() function gets the absolute value of the list, or the length.  When you subtract 1 from this value, you obtain the index of the last item in the list.

When range is used with one variable, (e.g., for i in range(10)), it will iterate from the 0 and increment by 1 by default.  The iteration will end after it has completed x passes where x is the number provided.  You can rewrite the default "for i in range(10)" to have the same functionality with three variables.  The default functionality of range when only one integer is passed is to implicitly have a "0," to the left and a ", 1" to the right of the number.  That is because the 0 is the starting number by default and 1 is the incremental value by default.  

Here is an example of two different (two-line) programs that have identical functionality:

range3.py:

for indexnum in range (0, 10, 1):
  print indexnum

defaultrange.py:

for indexnum in range (10):
  print indexnum

The range function can iterate starting from the rightmost item in the list and work its way backward.  To do this, use the range built-in function (and reserved word) with three parameters.  Here is an example:

coolList = [ "firstItem", "SecondITEM", "3rd Item", "4th item", "FIFTH ITEM (5)", "Sixth (6th) item"]
for x in range ( len(coolList), 0, -1 ):
  print x, coolList[x-1]

Leave a comment

Your email address will not be published. Required fields are marked *