Reverse 7/15 error:IndexError: list index out of range


#1

def reverse(text):
    c = len(text)
    b = []
    m = []
    for a in text:
        b.append(a)

    while True:
        m.append(b[c])
        c -=1
        if len(m) == len(b):
            break
    return m
    
print reverse('asf')

i get error:

Oops, try again. Your code looks a bit off--it threw a "list index out of range" error. Check the Hint if you need help!

#2

I added a print statement:

def reverse(text):
    c = len(text)
    b = []
    m = []
    for a in text:
        b.append(a)
        
    while True:
        print c
        m.append(b[c])
        c -=1
        if len(m) == len(b):
            break
    return m
    
print reverse('asf')

as you can see, i ask it to print c, which will print 3. Your list might contain 3 items, they are indexed at 0,1,2. Oops, list index out of range error. Hopes this helps, if more help is required, post an updated version of your code


#3

def reverse(text):
    c = len(text) - 1
    b = []
    m = []
    for a in text:
        b.append(a)
        
    while True:
        m.append(b[c])
        c -=1
        if len(m) == len(b):
            break
    return ''.join(m)


print reverse('asd')

It works (Finally) Thank you!!!
But why this version dosen't work?

def reverse(text):
    c = len(text) - 1
    b = []
    m = []
    for a in text:
        b.append(a)
        
    while True:
        m.append(b[c])
        c -=1
        if len(m) == len(b):
            break
    ''.join(m)
    return m


print reverse('asd')

output:
['d', 's', 'a']

#4

Because you don't store your join action anywhere?
if you add a print statement:

def reverse(text):
    c = len(text) - 1
    b = []
    m = []
    for a in text:
        b.append(a)
        
    while True:
        m.append(b[c])
        c -=1
        if len(m) == len(b):
            break
    
    print ''.join(m)
    return m


print reverse('asd')

you will see, it gets joined nicely, but saved nowhere, you could change print ''.join(m) to m = ''.join(m)


#5

Or simply,

    return ''.join(m)

#6

wasn't that the question? Why return ''.join(m) did work, and:

    ''.join(m)
    return m

didn't work?


#7

D'oh! Short term memory... Out of sight, out of mind. Lost my train of throught reading down the thread. Pardon me.