Main Content

Stepping through a list (or an array) in reverse order

Archive - Originally posted on "The Horse's Mouth" - 2012-03-23 08:12:59 - Graham Ellis

If you want to iterate through a list in reverse order, you can do so by stepping over (iterating through) the indexes of the list in reverse order. So in Python, for example, you would use range (or xrange for a potentially long list) with an increment of -1, giving the final index number as the start point and the beginning as the end:

  have = [20,40,60]
  for p in range(len(have)-1,-1,-1):
    print p, have[p]


Remember that Python's range starts at the first value given, but stops short of the terminating value. So you need to stop at "-1" to ensure that you process element number 0

If you're happy to have the list altered, many languages include a reverse function. Again in Python:

  have.reverse()
  for val in have:
    print val


Or you could use a "pop" fucntion to keep removing and returning the final item until the list is empty. Let's see that in Perl for a change:

  @numbers = (4,8,7,34);
  while ($val = pop @numbers) {
    print "$val\n";
    }


Full Python example is [here]. These techniques also apply to other languages with "ordered collections" - whether they're known as lists, arrays, tuples, tables, or vectors.