Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Functional Python Functional Workhorses Map

Andy McDonald
Andy McDonald
Python Development Techdegree Student 6,418 Points

Can I count in reverse order with range?

I recall being able to count backwards with range but have not really been able to do so with a couple of blocks I've tried to use. When I pass a -1 as the third arg in range nothing seems to happen. Am I doing something wrong here?

backwards = [
    [5, 4, 3, 2, 1],

def reverse(arg):
    letlist = []
    for char in arg:
    newword= []
    count = len(letlist)
    for i in range(count, -1):
    return newword


1 Answer

Instead of for i in range(count, -1):, you could try for i in range(count, 0, -1): so that i will start at the value of count and continue until i is not greater than 0. This will give you an IndexError: list index out of range for its first value of i, since letlist[len(letlist)] is not valid. Using range(count - 1, -1, -1) would solve that issue.

You could simplify your code by returning args[::-1].

In Python, the first element of a list is at index 0.

len(letlist) gives you the number of elements in letlist. If letlist has 100 elements, then len(letlist) would be 100. The first element in letlist would be at letlist[0] and its last element at letlist[99], which is also letlist[-1]. You get an IndexError if you try letlist[100] when the length of letlist is less than 101.