7.Reverse: lists and Quotations


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096


I can't identify why the elements in my list will not join together

My error message: Oops, try again. Your function fails on reverse("Python!"). It returns "['!', 'n', 'o', 'h', 't', 'y', 'P']" when it should return "!nohtyP".

I expected each element in my list to be concatenated into a string.


def reverse(text):
    n = len(text)
    letters = list(text)
    reversed_letters = []
    s = '-'
    d = ''
  
    for i in range(n):
        reversed_letters += letters[n-1-i]
    return(reversed_letters)
    
       
    reversed_word = s.join(reversed_letters)
    #reversed_word = d.join(reversed_letters)
    
    return(reversed_word)

I noticed that after I return the reversed_letters, I get back a list of elements with single guotes around them. I am trying to understand how to properly use the .join function. Could it be that I created a list of single quote elements when it would be double?


#2

@destinei_12: Hello, Destinei!
Why are you using two return statements? It will always execute the first one, since right after you leave the loop instruction, you use return(reversed_letters) and the execution of your program will go back to where it was called and due to that your join function won't be used at all (also the other return won't be executed as well).

Try to remove it and check the output!

Also, why are you using s = '-' and using such to join each character? Will it print the expected output or not?

Hope this helps!


#3

I tried removing the first return statement but it created another error : Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "list indices must be integers, not str" error.

for now lets say that I remove everything after my first return statement (since everything was working up until that point)

def reverse(text):
    n = len(text)
    letters = list(text)
    reversed_letters = []
    s = '-'
    d = ''
  
    for i in range(n):
        reversed_letters += letters[n-1-i]
    return(reversed_letters)

I would now like to join my elements together in a list. If I want to used reversed_word = s.join(reversed_letters) as the next line of code, what should my s be? or am I missing something before that even happens?


#4

return ''.join(reversed_letters)

#5

ok! Thank you for that great suggestion mtf!

This is my final code that came out correct

def reverse(text):
    n = len(text)
    letters = list(text)
    reversed_letters = []
    s = ''
   
    for i in range(n):
        reversed_letters += letters[n-1-i]
   
    
    return s.join(reversed_letters)

Thank you both!!!


#7