Changing the loop order

It is sometimes useful to loop through a set of values in a different order - perhaps reversed, or even sorted is some particular order. Normal for loops aren’t great at that, but Python makes this sort of thing much easier.

Using range() to count backwards - ugly

A range normally counts from zero up to but not including the end value. Eg this loop runs from 0 to 9:

for i in range(10):
    print(i)

What if we wanted to count backwards? Well, range has a 3 parameter variant, where you specify the start value, end value and a step value. If we make the step -1, then the loop will count backwards. So we need to use the highest value You might think this would work:

for i in range(10, 0, -1):       #Wrong!
    print(i)

In fact this counts from 10 down to but not including 0 (ie it counts down from 10 to 1). What we actually need is this:

for i in range(9, -1, -1):
    print(i)

This counts from 9 down to 0, but it is quite ugly (especially the end point being -1).

reversed()

Here is a better way, using the reversed function:

for i in reversed(range(10)):
    print(i)

This code is pretty much self documenting. It loops over a reversed range(10), which does exactly what you might expect, counts from 9 down to 0.

reversed takes the range object, and returns an iterator that provides the elements in reverse order. reversed also works with all sequences such as lists, tuples and strings. Here is an example of reversing a list:

k = ['red', 'green', 'blue']
for s in reversed(k):
    print(s)

This prints ‘blue’, ‘green’, and ‘red’.

reversed works with all sequences. Generally it does not work with iterables that are not sequences - for example it does not work with generators. The range object is a special case - it supports the __reversed()__ method, which allows it to work with reversed. See python.org for more details.

sorted()

The sorted function lets you loop over a sequence in sorted order. Here is an example:

k = [5, 6, 1, 8, 2, 3]
for s in sorted(k):
    print(s)

It prints 1, 2, 3, 5, 6, 8.

By default, sorted uses the natural sort order of the values - that is, the elements are compared using the equivalent of the less than operator. You can reverse the sort order using the optional reverse parameter (default false):

k = [5, 6, 1, 8, 2, 3]
for s in sorted(k, reverse=True):
    print(s)

You can use the optional key parameter to modify the sort order. That isn’t covered here, refer to the main Python documentation at python.org for more information.

sorted works with all iterables (which includes all types of sequences).

In summary, if you need to loop over a sequence in reversed or sorted order, use the reversed and sorted functions. It simplifies your code by removing extra logic, and it makes the intent of the code clear.