Changing the loop order

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

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):

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!

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):

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


Here is a better way, using the reversed function:

for i in reversed(range(10)):

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):

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 for more details.


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):

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):

You can use the optional key parameter to modify the sort order. That isn't covered here, refer to the main Python documentation at 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 Functional Programming in Python, or other books, by the same author.


Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020