A list comprehension that actually worked

I came up with a list comprehension that actually worked. I built it successively from separate lines of code until I got it down to just one line:

def reverse_string(word):

  return "".join([word[len(word) - x - 1] for x in range(len(word))])

To understand how I got here, see below

[word[x] for x in range(len(word))]

is the same thing as list(word), which of course returns a list of single characters for word.

Example:

print(list("Codecademy")) 
['C', 'o', 'd', 'e', 'c', 'a', 'd', 'e', 'm', 'y']

is identical to

print([word[x] for x in range(len(word))]) 
['C', 'o', 'd', 'e', 'c', 'a', 'd', 'e', 'm', 'y']

Now, to reverse the sequence, you just offset the subscript for word[ x ] by the length of word but zero based since python indexes begin at 0. So, now you have:

[word[len(word) - x - 1] for x in range(len(word))]

This returns the list of characters from word in reverse, which is very close to what we want, but now to get that back into a string you can use the join() member function of a null string because we do not want any delimiters to be added back between each letter using:

"".join(a_list) or
"".join([word[len(word) - x - 1] for x in range(len(word))])

Last but not least, we want to return this new string with:

return "".join([word[len(word) - x - 1] for x in range(len(word))])

1 Like

It is simpler, if you use slicing.