Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Functional Python Functional Workhorses Map

Andy McDonald
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Andy McDonald
Python Development Techdegree Graduate 13,801 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?

maps.py
backwards = [
    'tac',
    'esuoheerT',
    'htenneK',
    [5, 4, 3, 2, 1],
]

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

print(reverse('words'))

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.