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 trialAndy McDonald
Python Development Techdegree Graduate 13,801 PointsCan 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 = [
'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
jb30
44,807 PointsInstead 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]
.
Andy McDonald
Python Development Techdegree Graduate 13,801 PointsAndy McDonald
Python Development Techdegree Graduate 13,801 Pointswhy is len(letlist) not valid?
jb30
44,807 Pointsjb30
44,807 PointsIn Python, the first element of a list is at index 0.
len(letlist)
gives you the number of elements inletlist
. Ifletlist
has 100 elements, thenlen(letlist)
would be 100. The first element inletlist
would be atletlist[0]
and its last element atletlist[99]
, which is alsoletlist[-1]
. You get an IndexError if you tryletlist[100]
when the length ofletlist
is less than 101.Andy McDonald
Python Development Techdegree Graduate 13,801 PointsAndy McDonald
Python Development Techdegree Graduate 13,801 PointsGotcha. Thank you so much!