Changing the loop order


Martin McBride, 2018-03-02
Tags range reversed sorted for loop
Categories python language intermediate python

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.

If you found this article useful, you might be interested in the book Python Quick Start or other books by the same author.

Prev

Popular tags

2d arrays abstract data type alignment and animation arc array arrays behavioural pattern bezier curve built-in function callable object chain circle classes close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data types design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object index inner function input installing iter iterable iterator itertools l system lambda function len line linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path pattern permutations polygon positional parameter print pure function python standard library radial gradient range recipes rectangle recursion reduce repeat rgb rotation scaling sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle tuple turtle unpacking user space vectorisation webserver website while loop zip