Changing the loop order

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

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.

See also

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

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

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